我有一个列表视图,其中第一列是复选框,用于启用/禁用代表所述行的项。问题是,当我更改复选框时,它没有选择行。因此,当我在checkBox checked/unchecked事件中执行listView.SelectedItem
时,它为空并崩溃。是否有任何方法来修复这种行为,使listView检查将选择项目?或者,如果WPF中有一个等效的CheckedItems
属性,就像在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}" />
</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);
}
您可以使用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;
}