c# - 从ViewModel中选择 ListView 中的所有项目

标签 c# wpf mvvm visual-studio-2012

我在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/

相关文章:

c# - 动态创建列表 C#

c# - 仅在加载 (.NET) DLL 时才执行功能的最佳方法?

c# - WPF WebBrowser 控件 - 如何抑制脚本错误?

wpf - 关于 WPF xaml 中的数据模板或样式的问题

c# - 我不明白持久独立性的意义

c# - 在 C# 中,List<struct> 中的值是否已装箱?

c# - 为什么当 this.DataContext = this 时绑定(bind)到我的类的实例不起作用

swift - 在 swift 中使用内部结构时引用包含类的属性

c# - 从现有 View 模型访问 View 模型的正确方法

c# - 通过 WPF 命令模式启用提交/取消按钮