1

I have a listview with two columns, one contains a textbox and the other a checkbox. These are bound to an ObservableCollection of a custom object containing a string for the textbox and a boolean for the checkbox.

All was working well until I tried having the check event of the checkbox highlight it's the row in the listview as in this article.

My problem is that checkbox no longer binds to the ObservableCollection. The textbox binds okay, but changing the checbox declaration from:

<CheckBox IsChecked="{Binding RestrictedEdit}"/>

to this:

<CheckBox IsChecked="{Binding RestrictedEdit, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}"/>

stops the checkbox binding and the listview is displayed with the checkboxes all unchecked irrespectivate of status of the boolean. What am I doing wrong?

Community
  • 1
  • 1
GrandMasterFlush
  • 6,269
  • 19
  • 81
  • 104

2 Answers2

2

You are trying to bind to RestrictedEdit property, which ListViewItem doesn't have. This property is declared in view model, which is stored in DataContext, so this should work:

<CheckBox IsChecked="{Binding DataContext.RestrictedEdit,
                              RelativeSource={RelativeSource FindAncestor,
                                              AncestorType={x:Type ListViewItem}}}"/>

However, I don't see any reason to use this code instead of simple IsChecked="{Binding RestrictedEdit}". CheckBox inherits DataContext from ListViewItem, so there is no reason to use relative source.

max
  • 33,369
  • 7
  • 73
  • 84
  • 1
    Thanks for taking the time to explain. I've looked over several articles on doing what I want and it looks like I've got a couple of the examples mixed up. That's working perfectly now plus I understand how the relative bindings work, cheers! – GrandMasterFlush Jun 29 '12 at 11:04
0

Let the binding as it is (no RelativeSource) and use rather a style or a DataTemplate having your custom object class as TargetType, and with a DataTrigger set on RestrictedEdit. example with style :

<Style x:Key="MyStyle" TargetType="MyClass">
  <Setter Property="BackGround" Value="White" />
  <Style.Trigger>
     <DataTrigger Binding="{Binding RestrictedEdit}" Value="False">
         <Setter Property="BackGround" Value="Gray" />
      </DataTrigger>
  </Style.Trigger>
</Style>

Define this style, say, in your application resources (in App.xaml). Then in your listview, use :

ItemContainerStyle="{StaticResource MyStyle}"
GameAlchemist
  • 18,995
  • 7
  • 36
  • 59