Question

I thought {Binding DataContext.foo} and {Binding foo} were identical until I came across an issue binding a selection changed event from a ComboBox to a command in my ViewModel.

I was doing it like so...

<i:EventTrigger EventName="SelectionChanged">
     <cmd:EventToCommand Command="{Binding DataContext.TestCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Page}}}" />
</i:EventTrigger>

Using DataContext.TestCommand works while just specifying TestCommand appears to fail. I've never encountered a difference between the two can anyone explain it?

Was it helpful?

Solution

They're binding to two subtly different things:

"Binding DataContext.TestCommand" is binding to the TestCommand property of the Datacontext (presumably the context defines that property) of your Page.

"Binding TestCommand" is binding to the TestCommand property of the Page itself, which in this case probably doesn't exist, which is why it doesn't work.

There's a neat program called WPF Snoop that you can use to inspect the bindings whilst things are running (often helps me make sense of things when I'm, stuck).

OTHER TIPS

Almost each element in visual tree (View) is linked to the data layer (ViewModel) per DataContext property. Of course the data layer tree is much more simpler because most controls just inherit from their parent.

By default a Binding is looking for the Path in data layer. But if you specify a RelativeSource (like RelativeSource.Self or with AncestorType) or an ElementName the Binding switches to visual layer and searches in controls for the bound property. With DataContext you can go back to data layer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top