Wpf – ListView ItemContainerStyle Template

bindingwpfwpf-controls

I created style to be used as my ListView's item template that contains a CheckBox and a TextBlock:

<Style x:Key="CheckBoxListStyle" TargetType="{x:Type ListView}">
            <Setter Property="SelectionMode" Value="Multiple"></Setter>
            <Setter Property="ItemContainerStyle">
                <Setter.Value>
                    <Style TargetType="{x:Type ListViewItem}" >
                        <Setter Property="Template">
...

The checkbox in the template is bound to the IsSelected property of the list view item:

<CheckBox x:Name="itemCheckBox" Width="13" Height="13" Focusable="False" IsChecked="{Binding Path=IsSelected, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">

And the textblock's text is bound to the Value property of the source of the list view item:

<TextBlock x:Name="textBlock" Padding="5,0,0,0" HorizontalAlignment="Stretch">
  <ContentPresenter Content="{Binding Path=Value}"/>
</TextBlock>

Each of the items in my list is an object that contains two properties, Value and IsChecked. What I am trying to do is bind the IsChecked property of my object to the IsSelected property of my list view item. However, I do not know how to access the IsChecked property of my object from within the ListViewItem template.

I didn't have any trouble binding the content of the text block to the Value property of my object but where would I even put the binding definition if I want the IsChecked property of my object to be bound to the IsSelected property of the list view item?

Best Answer

The DataContext for each ListViewItem should be set to the item data when it is created by the parent ListView so you should be able to use:

<Style TargetType="{x:Type ListViewItem}" >
    <Setter Property="IsSelected" Value="{Binding IsChecked}">
    ...
</Style>
Related Topic