【问题标题】:Invoking multiple command targets from a single command source从单个命令源调用多个命令目标
【发布时间】:2012-09-30 21:38:06
【问题描述】:

我需要调用一个命令的多个实例

对于本例,我将采用 2 个控件“A”和“B”

'A' 是调用者,'B' 是调用者,'B' 有多个实例

控件:

 public class A : Control 
 {
     public A()
     {}

     public ICommand OnACommand   
     {
        get { return (ICommand)GetValue(OnAProperty); }
        set { SetValue(OnACommandProperty, value); }
     }

    public static readonly DependencyProperty OnACommandProperty =
        DependencyProperty.Register("OnACommand", typeof(ICommand), typeof(A), new UIPropertyMetadata(null));

     public bool Something   
     {
        get { return (bool)GetValue(SomethingProperty); }
        set { SetValue(SomethingProperty, value); }
     }

    public static readonly DependencyProperty SomethingProperty=
        DependencyProperty.Register("Something", typeof(bool), typeof(A), new UIPropertyMetadata(false,OnSometingPropertyChanged));

    private static void  OnSometingPropertyChanged(...)
    {
        ... 
        OnACommand.Execute(this.Value);
    }                  
 }


 public class B : Control 
 {
     public B(){ }

     public ICommand OnBCommand   
     {
        get { return (ICommand)GetValue(OnBCommandProperty); }
        set { SetValue(OnBCommandProperty, value); }
     }

    public static readonly DependencyProperty OnBCommandProperty =
        DependencyProperty.Register("OnBCommand", typeof(ICommand), typeof(B), new UIPropertyMetadata(null));              
 }

绑定:

   <local:B  x:Name="B1" OnBCommand="{Binding ElementName=A1 , Path=OnACommand />
   <local:B  x:Name="B2" OnBCommand="{Binding ElementName=A1 , Path=OnACommand />   
   <local:A  x:Name="A1"  />   

我需要的是在执行 OnACommand 时执行绑定到该 A 命令的所有 B 命令。

我认为唯一可行的方法是,如果我 在 B 中实现命令将其绑定到 OneWayTosource ,但只有最后一个绑定到 A 会成为将被执行的 B。

  public B()
  {
       OnBCommand = new RelayCommand<int> 
                    (
                        value => { this.Value = value ....}
                    );
  }

   <local:B  x:Name="B1" 
             OnBCommand="{Binding ElementName=A1,Path=OnACommand,Mode=OneWayToSource />
   <local:B  x:Name="B2" 
             OnBCommand="{Binding ElementName=A1,Path=OnACommand,Mode=OneWayToSource />   
   <local:A  x:Name="A1"  />   

如果我以任何其他方式绑定它,比如 OneWay,我需要在 A 中实现命令,而 B 不知道 它甚至已被执行,除非有可能以某种方式从 B 中的委托确认执行 ..

所以总结一下,我需要从一个来源执行多个目标。

此外,我可能会指出,我使用我在“A1”中声明的常规 .net 事件解决了这个问题 并订阅了所有 B,但由于这是用 MVVM 编写的 WPF,我正在寻找使用命令的 MVVM 样式方式来执行此操作。

提前致谢。

【问题讨论】:

    标签: wpf mvvm binding command


    【解决方案1】:

    实现您想要完成的工作的一种可能方法是使用composite command

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 2014-05-23
      • 2014-08-20
      • 2021-07-05
      相关资源
      最近更新 更多