简体   繁体   English

WPF listView 获取检查项

[英]WPF listView Getting Checked Item

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.因此,当在我的 checkBox 选中/未选中事件中执行listView.SelectedItem ,它为空并崩溃。 Is there any way to fix this behavior so the listView check will select the item?有什么方法可以解决此行为,以便 listView 检查将选择该项目? Or, if there is an equivalent CheckedItems property in WPF like there is in WinForms?或者,如果 WPF 中存在与 WinForms 中相同的CheckedItems属性?

XAML: 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}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

C#: 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);
}

You can use the DataContext to access the ViewModel and manually select it (if it is desired).您可以使用DataContext访问ViewModel并手动选择它(如果需要)。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM