I\'m fairly new to XAML but enjoying learning it. The thing I\'m really struggling with is binding a property to an element in a DataTemplate
.
I have create
When you are in a DataTemplate, your DataContext is the data templated object, in this case an Item
. Thus, the DataContext of the CheckBox in the DataTemplate is an Item
, not your ItemViewModel
. You can see this by your <TextBlock Text="{Binding ItemName}"/>
, which binds to a property on the Item
class. The Binding to IsCheckBoxVisible is trying to find a property called IsCheckBoxVisible on Item
.
There are a couple of ways around this, but by far the easiest is to do this:
On your Window (in the xaml), give it and x:Name. Eg:
<Window [...blah blah...]
x:Name="MyWindow">
Change your binding to look like this:
<CheckBox Grid.Column="1"
Visibility="{Binding DataContext.IsCheckBoxVisible, ElementName=MyWindow, Converter={StaticResource VisibilityConverter}}">
We're using the Window as the source for the Binding, then looking at its DataContext property (which should be your ItemViewModel
, and then pulling off the IsCheckBoxVisible property.
Another option, if you want something fancier, is to use a proxy object to reference your DataContext. See this article on DataContextProxy.