如何在不破坏MVVM的情况下向xamdatagrid cellactivated事件添加命令

时间:2012-10-22 15:19:28

标签: wpf commandbinding xamdatagrid

我正在使用XamDataGrid来显示我的数据。现在我想为每列添加不同的命令。

在整个网格上使用CellActivated事件然后绑定到ActiveCell将无法工作,因为Viewmodel必须知道View以及如何从ActiveCell返回的对象中评估Column。

我正在寻找一种方法告诉XamDataGrid应该调用哪个命令。

我想象这样的事情:

<igDP:Field Name="Dev"                  >
   <igDP:Field.Settings>
      <igDP:FieldSettings CellValuePresenterStyle="{StaticResource DevStyle}" ActivateCommand="{Binding DevCommand}/>
   </igDP:Field.Settings>
</igDP:Field>

我真的不在乎命令必须是我的viewmodel或dataitem的属性。

我该如何实现?

谢谢

1 个答案:

答案 0 :(得分:1)

Attached BehaviorMVVM齐头并进。

通过附加行为处理您的事件并向其提供Viewmodel.ICommand,它将在处理事件时执行。然后,您可以将处理事件中的事件args发送到ViewModel.ICommand as命令参数。

您的附属财产

 public static class MyBehaviors {

    public static readonly DependencyProperty CellActivatedCommandProperty
        = DependencyProperty.RegisterAttached(
            "CellActivatedCommand",
            typeof(ICommand),
            typeof(MyBehaviors),
            new PropertyMetadata(null, OnCellActivatedCommandChanged));

    public static ICommand CellActivatedCommand(DependencyObject o)
    {
        return (ICommand)o.GetValue(CellActivatedCommandProperty);
    }

    public static void SetCellActivatedCommand(
          DependencyObject o, ICommand value)
    {
        o.SetValue(CellActivatedCommandProperty, value);
    }

    private static void OnCellActivatedCommandChanged(
           DependencyObject d, 
           DependencyPropertyChangedEventArgs e)
    {
        var xamDataGrid = d as XamDataGrid;
        var command = e.NewValue as ICommand;
        if (xamDataGrid != null && command != null)
        {
           xamDataGrid.CellActivated +=
              (o, args) =>
                 {
                     command.Execute(args); 
                 };
        }
    }
}

您的XAML:

 <infragistics:XamDataGrid ...
        local:MyBehaviors.CellActivatedCommand="{Binding MyViewModelCommand}" />

希望它有所帮助。