Binding to a viewmodel property in a DataTemplate

前端 未结 1 483
小鲜肉
小鲜肉 2021-02-06 03:18

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

相关标签:
1条回答
  • 2021-02-06 03:33

    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.

    0 讨论(0)
提交回复
热议问题