在 WPF Caliburn.Micro 中单击按钮时无法在 DataGrid 中选择"全部"



我正在尝试弄清楚如何使用MVVM(Caliburn.Micro(bindbutton来选择DataGrid中的所有rows(项目(。

我希望将此按钮与DataGrid本身分开。

像这样:

视图:

<Button x:Name="SelectAll"/>
<DataGrid x:Name="People">
<DataGrid.RowStyle>
<Style>
<Setter Property="DataGridRow.IsSelected"
Value="{Binding IsPersonSelected}" />
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding PersonName, UpdateSourceTrigger=PropertyChanged}" />
</DataGrid.Columns>
</DataGrid>

视图模型:

public bool _isPersonSelected = false;
public bool IsPersonSelected
{
get { return _isPersonSelected; }
set 
{ 
_isPersonSelected = value;
NotifyOfPropertyChange(() => IsPersonSelected);
}
}
public void SelectAll()
{
if(IsPersonSelected == true)
{
IsPersonSelected = false;
}
else
{
IsPersonSelected = true;
}
}

但这不起作用,也许还有另一种方法可以使用 MVVM 的某种绑定来选择DataGrid中的行?

还是某种称呼SelectAllCommandRoutedUICommandDataGrid的方式?

建议/帮助将不胜感激。

我没有看到你对类和模型的定义,所以我想你有 IsPersonSelected 是你的类的属性? 你试过吗?

public class PersonModel:PropertyChangedBase
{
:
:
public bool IsPersonSelected
{
get => _isPersonSelected;
set
{
_isPersonSelected = value;
NotifyOfPropertyChange(() => IsPersonSelected);
}
}
}
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="IsSelected"  Value="{Binding IsPersonSelected, Mode=TwoWay}"/>
</Style>
</DataGrid.RowStyle>

之后与 SelectAll((

是吗:

public  void SelectAll()
{
foreach(var p in People)
if(p.IsPersonSelected)
//DO something
{

如果选择多行,则可以看到此行的值为 true 在您可以通过修改 IsPersonSelected 的值来更改选择内容后,如果不突出显示数据网格的相应行,则属性 IsSelected 不会重现所选行的突出显示,为此,这是另一个问题(使用可视化助手(。要重现程序选择的行的突出显示,它稍微复杂一些,需要更改编码并需要具有完整的代码 wpf。


另一种不使用属性 IsSelected 选择多行的方法:

添加xmlns:cal="http://www.caliburnproject.org"

<DataGrid x:Name="People" cal:Message.Attach="[Event SelectionChanged] = [Row_SelectionChanged($eventArgs)]">

在您的视图中模型:

public void Row_SelectionChanged(SelectionChangedEventArgs obj)
{
//(obj.OriginalSource as DataGrid).SelectedIndex gives you the index of row selected
_selectedObjects.AddRange(obj.AddedItems.Cast<PersonModel>());
obj.RemovedItems.Cast<PersonModel>().ToList().ForEach(w => _selectedObjects.Remove(w));
}
List<PersonModel> _selectedObjects = new List<PersonModel>();
public PersonModel SelectedPeople { get; set; } //Will be set by Caliburn Micro automatically (name convention)

每次选择一行时,它都会添加到列表中,使用 Ctrl 可以添加更多行或取消选择一行。每个事件都会修改列表的内容。(对不起我的英语,希望你能理解(。仅供参考,使用 caliburn,您可以访问名称约定,因此就像您的数据网格被命名为"人员"一样,所选的第一行会自动绑定到"选定人员">

最新更新