我的WPF窗口上有一个ListView,我有一个按钮,可以选择全部。首先,如何让按钮执行选择列表视图中的所有项目。
其次,我需要我的ViewModel然后浏览所有选定的项目。如何在ViewModel中获取此信息?
我已经读过你可以使用IsSelected属性执行此操作但有一个错误,其中本地属性会覆盖绑定属性,因此如果之前已经选择它,则它似乎不再被选中 - 或类似的东西。这似乎令人费解。 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" />
答案 0 :(得分:3)
在按钮上附加处理程序 -
<Button Click="Button_Click"/>
在ListView实例上调用SelectAll
方法 -
private void Button_Click(object sender, RoutedEventArgs e)
{
sources_ListView.SelectAll();
}
其次,如果在View上选择了所有项目,那么ItemsSource
将始终等于SelectedItems
。因此,只需遍历ItemsSource即Sources
即可。
答案 1 :(得分:0)
我创建了一种行为,允许控件中的属性绑定到项集合的属性,其方式如下:
您可以使用它将CheckBox.IsChecked绑定到此类型元素集合中的类型的IsSelected属性。 我建议那个想要做类似于你想要的东西但是使用DataGrid的人。您可以查看它here。
答案 2 :(得分:0)
我很久以前创建了一个附加行为来处理这个问题。它允许您将SelectedItems列表绑定到View Model上的可观察集合,并处理来回穿梭的更改。
使用附加行为是将功能扩展到现有控件(而不是子控件控件)的首选方法,否则需要大量的视图逻辑。
我不会说你应该总是使用这种方法而不是在视图中放置逻辑。但它是捕获行为以便于重复使用的简单方法。
答案 3 :(得分:0)