23

I'm trying to find out where the items in a HeaderedContentControl come from in a project that's not mine. Here's the code:

        <HeaderedContentControl 
            Content="{Binding Path=Workspaces}"
            ContentTemplate="{StaticResource WorkspacesTemplate}"
            Header="Workspaces"
            Style="{StaticResource MainHCCStyle}" 
            DataContext="{Binding}" // <--- this 
       />

<DataTemplate x:Key="WorkspacesTemplate">
<TabControl 
  IsSynchronizedWithCurrentItem="True" 
  ItemsSource="{Binding}" 
  ItemTemplate="{StaticResource ClosableTabItemTemplate}"
  Margin="4"
  />

so let's examine it:

  1. ContentTemplate attribute describes how the items are desplayed.
  2. WorkspacesTemplate sets ItemsSource's attribute to {Binding} meaning it's bound to its DataContext property (DataContext of HeaderedContentControl)
  3. So I look at HeaderedContentControl's dataContext, but it is described as "{Binding}" as well...

What does that mean?

Ivan Prodanov
  • 34,634
  • 78
  • 176
  • 248

2 Answers2

27

Without seeing more of your code it is hard to be certain, but DataContext="{Binding}" is quite often unnecessary, as any object in the current binding context will automatically have its DataContext property set to the equivalent of {Binding}.

Remember:

  • Property="{Binding}" means "set this.Property to the evaluated value of this.DataContext"
  • Property="{Binding Path=SubProperty}" means "set this.Property to the evaluated value of this.DataContext.SubProperty"
  • etc

This means that DataContext="{Binding}" means "set this.DataContext to the evaluated value of this.DataContext", which (in most cases) is redundant!

Steve Greatrex
  • 15,789
  • 5
  • 59
  • 73
  • 5
    I'm intrigued by the "in most cases". When is it not redundant? – Grhm Dec 20 '12 at 09:22
  • 3
    On it's own I'm *pretty* sure it's always redundant, but there are some valid use cases if you include converters, update triggers etc. to change the behaviour of the binding – Steve Greatrex Dec 20 '12 at 09:31
  • 2
    The most common use is to reset a DataContext on controls that have inheritted an overriden DataContext from their parent, back to the original value. – Tom Deloford Oct 12 '14 at 15:18
  • 2
    "reset a DataContext" makes no sense. `DataContext="{Binding}"` is always redundant. Anybody who claims to know about a "valid use" case should be more specific, ideally just show it. – Clemens Mar 27 '22 at 17:16
5

{Binding} is something like bind 'this' or current data context - assigned or inherited from parents. For better understanding, equivalent for {Binding} is {Binding .} or {Binding Path=.}

y0j0
  • 3,369
  • 5
  • 31
  • 52