Home > OS >  WPF listView Getting Checked Item
WPF listView Getting Checked Item

Time:10-12

I have a list view, of which the first column is checkboxes to enable/disable the item which represents said row. The problem is, when I change the checkbox, it does not select the row. Thus, when inside my checkBox checked/unchecked event I do listView.SelectedItem, it is null and crashes. Is there any way to fix this behavior so the listView check will select the item? Or, if there is an equivalent CheckedItems property in WPF like there is in WinForms?

XAML:

<Grid>
    <ListView x:Name="listView1" HorizontalAlignment="Left" Height="300" Margin="10,10,0,0" VerticalAlignment="Top" Width="375">
        <ListView.View>
            <GridView>
                <GridViewColumn x:Name="StatusHeader" Header="Status" Width="50">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox Margin="5, 0" IsChecked="{Binding loaded}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>

                <GridViewColumn x:Name="NameHeader" Header="Name" Width="130" DisplayMemberBinding="{Binding name}" />
                <!--<GridViewColumn x:Name="MappedAddressHeader" Header="Mapped Address" Width="130" DisplayMemberBinding="{Binding address}" />-->
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

C#:

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    module v = (module)listView1.SelectedItem; // crash
    _client.AddClientModule(v.path);
}

private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
    module v = (module)listView1.SelectedItem; // crash
    _client.RemoveClientModule(v.name);
}

CodePudding user response:

You can use the DataContext to access the ViewModel and manually select it (if it is desired).

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    var cb = (CheckBox)sender;
    var v = (module)cb.DataContext;

    _client.AddClientModule(v.path);

    // Select manually
    listView1.SelectedItem = v;
}

private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
    var cb = (CheckBox)sender;
    var v = (module)cb.DataContext;

    _client.RemoveClientModule(v.path);

    // Select manually
    listView1.SelectedItem = v;
}
  • Related