Search code examples
.netwpflistview

Get information about status of nested checkboxes in ListView in WPF


Here is the problem:

I have a ListView as following:

<UserControl.Resources>
    <DataTemplate x:Key="FirstCell">
        <StackPanel Orientation="Horizontal">
            <CheckBox Margin="2"></CheckBox>
        </StackPanel>
    </DataTemplate>
</UserControl.Resources>

<ListView Name="lvRights">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="100" Header="Select" CellTemplate="{StaticResource FirstCell}"/>
            <GridViewColumn Width="200" Header="Right" DisplayMemberBinding="{Binding Path=Name}" />
        </GridView>       
    </ListView.View>
</ListView>

I am binding the list to a collection of "Roles", which have only Id and Name. I am using that DataTemplate to display a checkbox in the first column.

And here is the question:

How can I know at runtime whether the user checked one of the checkboxes? In the .Items property of the listview I have the Roles, but I cannot get any information about the first column.


Solution

  • You can either

    1) add a click handler to the check box in the template. In the code behind you can cast the DataContext of the checkbox back to a Role to figure out which one it is.

    2) You can add some sort of boolean property to your Role class. You can then bind the IsChecked property of the checkbox to this boolean property. You may need a binding converter to converter between the boolean and the is checked property