我在WPF窗口上有一个ListView,并且有一个应该全选的按钮。首先,如何获取按钮以选择列表 View 中的所有项目。
其次,我需要ViewModel来浏览所有选中的项。如何在ViewModel中获取此信息?
我读过您可以使用IsSelected属性来执行此操作,但是有一个错误,即本地属性会覆盖binding属性,因此,如果在之前已选择了该属性,则不会再次选择它-或类似的东西。似乎令人费解。 The blog that looks into this problem
然后,我读了这个博客Data binding to selected items ,它似乎也很令人费解。
我想知道是否必须如此复杂,而这些例子是前进的唯一途径。
XAML:
<ListView Name="sources_ListView" Grid.RowSpan="1" ItemsSource="{Binding Path=Sources}">
<ListView.View>
<GridView>
<GridViewColumn Width="290" Header="Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=OriginalPath}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="80" Header="Type">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Type}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<Button Grid.Row="0" Grid.Column="0" Content="Select All" Name="selectAllSources_Button" Margin="3" />
<Button Grid.Row="0" Grid.Column="1" Content="Deselect All" Name="deselectAllSources_Button" Margin="3" />
<Button Grid.Row="0" Grid.Column="3" Content="Remove Selected" Name="removeSelected_Button" Margin="3" Width="100" HorizontalAlignment="Right" />
最佳答案
在按钮上附加一个处理程序-
<Button Click="Button_Click"/>
在ListView实例上调用
SelectAll
方法-private void Button_Click(object sender, RoutedEventArgs e)
{
sources_ListView.SelectAll();
}
其次,如果在View上选择了所有项目,则
ItemsSource
将始终等于SelectedItems
。因此,您可以简单地遍历ItemsSource,即Sources
。
关于c# - 从ViewModel中选择 ListView 中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590617/