如何在 WPF 中选择行时选中列表视图中的行,反之亦然
本文关键字:视图 列表 反之亦然 WPF 选择 | 更新日期: 2023-09-27 18:34:51
我有一个列表视图并使用视图作为网格视图,如下所示:
<ListView Grid.Row="1" Grid.Column="0" Height="100" HorizontalAlignment="Left" Margin="10,10,10,10" Name="listView2" VerticalAlignment="Top" Width="300" ItemsSource="{Binding}" SelectionChanged="listView2_SelectionChanged" SelectionMode="Multiple">
<ListView.View>
<GridView AllowsColumnReorder="True">
<GridViewColumn Header="Select">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=FirstName}" Header="First Name" Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=LastName}" Header="Last Name" Width="100"/>
</GridView>
</ListView.View>
</ListView>
现在的问题是,当用户选中复选框时,应该选择记录。此外,用户从列表中选择记录,则应选中相应的复选框。
怎么办?
我假设您的视图模型具有 IsSelected 属性:
public Boolean IsSelected
{
get { return isSelected; }
set
{
if (isSelected != value)
{
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
private Boolean isSelected;
因此,让我们更改标记:
<ListView ItemsSource="{Binding}" SelectionMode="Multiple">
<!-- add style for the item in list view: -->
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView AllowsColumnReorder="True">
<GridViewColumn Header="Select">
<GridViewColumn.CellTemplate>
<DataTemplate>
<!-- bind the checkbox to the IsSelected property: -->
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" Width="100"/>
</GridView>
</ListView.View>
</ListView>
最简单的方法:
<GridViewColumn Header="None">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Width="50"
Height="50"
IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}},
Path=IsSelected,Mode=TwoWay}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>