c# - 通过命令 (MVVM) 选择 ListView 中的所有项目

标签 c# wpf listview mvvm command

我的窗口中有 4 个 ListView,每个 ListView 都有一个 CheckBox 列,如下所示:
enter image description here

现在我想实现 1 个命令,我可以将它绑定(bind)到我拥有的每个 ListView 的标题中的 CheckBox。因此,如果单击标题中的 CheckBox,它将选择该 ListView 中的所有项目,如果再次单击,它将再次取消选择它们。

我知道通过后面代码中的点击事件很容易做到这一点,但我不认为这是符合 MVVM 的,是吗?

但我也不想在我的 ViewModel 中有 4 个不同的“IsSelected”属性,然后我可以像这篇文章中建议的那样绑定(bind)到 ListView 的样式:Select All items in ListView with MVVM

还有其他方法吗?是否可以将 ListView 控件作为命令参数发送?

我试过了:

  <ListView x:Name="UserDemandListView" Grid.Column="2" Grid.Row="2" MinWidth="200" ItemsSource="{Binding DemandLicenses}" Grid.RowSpan="2">
         <ListView.View>
              <GridView>
                  <!--<SnippetGridViewColumnCheckBox>-->
                    <GridViewColumn CellTemplate="{StaticResource FirstCell}" Width="25">
                       <CheckBox x:Name="CheckAll3" Content="" Command="{Binding SelectAllCommand}" CommandParameter="{Binding ElementName=UserDemandListView}" Margin="4,0,0,0"/>
                    </GridViewColumn>
                    <!--</SnippetGridViewColumnCheckBox>-->

但我命令中的参数始终为空。我想我的 WPF 技能有点生疏......

最佳答案

您应该只在 DemandLicenses 中设置对象的属性绑定(bind)到行级别 CheckBox
XAML

<ListView x:Name="UserDemandListView" Grid.Column="2" Grid.Row="2" MinWidth="200" ItemsSource="{Binding DemandLicenses}" Grid.RowSpan="2">
    <ListView.View>
        <GridView>
            <!--<SnippetGridViewColumnCheckBox>-->
            <GridViewColumn CellTemplate="{StaticResource FirstCell}" Width="25">
                <CheckBox x:Name="CheckAll3" Content=""  Margin="4,0,0,0" Checked={Binding CheckAllDemandLicenses}"/>
            </GridViewColumn>
            <!--</SnippetGridViewColumnCheckBox>-->

查看型号
// Property, that shows if all Items need to be checked
private bool _checkAllDemandLicenses;
public bool CheckAllDemandLicenses
{
    get
    {
        return _checkAllDemandLicenses;
    }
    set
    {
        _checkAllDemandLicenses = value;

        foreach(DemandLicense d in DemandLicenses)
        {
            // Set the property, that is bound to the row level checkbox
            d.Selected = value;
        }

        OnPropertyChanged("CheckAllDemandLicenses"); // Or whatever your implementation for INotifyPropertyChanged is
        OnPropertyChanged("DemandLicenses");
    }
}

这样,您不必将命令绑定(bind)到 CheckBox而且您不需要从您的 ViewModel 访问 View 元素。

关于c# - 通过命令 (MVVM) 选择 ListView 中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297428/

相关文章:

c# - 需要写一个总和(成绩)/总和(学分)代码

c# - WPF 窗口在 ListBox 项双击事件处理程序中弹出后失去焦点

c# - 我可以将一个网格层叠在另一个网格之上吗?

java - 带有 SimpleCursorAdapter 的 Android ListView - 恢复时崩溃

c# - 在 C# 中使用 List 字符串的 listview 显示错误

c# - 如何为 Visual Studio 2017 生成 odata v4 c# 代理客户端?

c# - 错误与 if else 和 View 中的标记

c# - 我应该使用 ObservableCollection 来处理图像吗

java - 自定义 ListView 适配器有 null NullPointerException 错误

c# - 转换器应该抛出任何类型的异常吗?