我需要调用一个命令的多个实例
对于这个例子,我将采用 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 中实现 Command并将其绑定到 OneWayTosource,但只有最后一个 Bind to A 将是 B ,它将被 Executed 。
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 中的委托确认执行。
所以总结一下,我需要从一个来源执行多个目标。
另外我可能会指出我使用常规.net事件解决了这个问题,我在'A1'中声明并订阅了所有B,但由于这是用MVVM编写的WPF,我正在寻找MVVM风格的方式来做到这一点,使用命令。
提前致谢。