gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:26:20 25 4
gpt4 key购买 nike

我的窗口中有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com