【问题标题】:Select All in DataGrid from button从按钮中全选 DataGrid
【发布时间】:2019-08-20 16:46:55
【问题描述】:

我在从 DataGrid 中选择所有行时遇到了一点问题。 问题是 CommandButton 位于引用 MainViewModel 的 UserControl 中,而网格位于引用另一个 ViewModel 的 UserControl 中。第一个想法是做一个静态方法,从mvm中调用,但是datagrid不是静态的,不能调用。我该怎么办?

编辑:

我实际上是通过从后面的代码中引用网格的静态实例来解决问题的。

在按钮视图模型中,我回顾了命令执行中的全选方法

 if (_CommandBtnSelectAll == null)
 {
    // creo una nuova istanza del comando
    _CommandBtnSelectAll = new USCommands(
       item =>
       {
             ViewControlCodeBehind.grid.SelectAll();
       }
 }

在后面的 ViewControl 代码中,我只需要设置一个新 DataGrid 的静态实例并将其分配给实际的数据网格。

public static DataGrid grid;

public ControlBody() // It's the UserControl initialization
{
   this.grid = DataGridControl; // DataGridControl is the name of the actual control
}

【问题讨论】:

  • Marco:请在您的帖子中添加相关代码,以便我们查看您的 xaml 的结构。很有可能您可以简单地利用继承的用户控件 DataContext 并将其作为 CommandParameter 传递给命令,然后可以在 ViewModel 上设置一个属性(例如 foreach(var item in viewModel.Items) item.IsSelected = true; 这将被 DataGrid 自动拾取(假设 ViewModel. Items 绑定到 DataGrid & IsSelected 绑定到 ItemContainer.IsSelected)如果您需要有关如何绑定它的更多信息,可以在 SO 上搜索 IsSelected 绑定。

标签: c# wpf xaml


【解决方案1】:

您可以从视图模型发送消息或事件,并使用信使或事件聚合器在视图中订阅和处理此事件。请参阅this 博客文章了解更多信息。

另一种选择是使用视图实现的接口注入视图模型here

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 2011-02-18
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多