WPF
是否有可能在容器级别声明Command
绑定?实际使用的情况是,如果有多个UIElements
绑定相同的Command
,那么它将更易于管理,并且需要更少的代码才能在容器级别上声明它。
所以,而不是做
<StackPanel>
<Button Command="{Binding MyCommand}"/>
<Button Command="{Binding MyCommand}"/>
<Button Command="{Binding MyCommand}"/>
</StackPanel>
将使用以下方式声明绑定
<StackPanel Command="{Binding MyCommand, TargetType="Button"}">
<Button />
<Button />
<Button />
</StackPanel>
编辑:我创建了一个公开命令的行为:
public class MouseMoveBehaviour
{
public static readonly DependencyProperty MouseMoveCommandProperty = DependencyProperty.RegisterAttached("MouseMoveCommand", typeof(ICommand), typeof(MouseMoveBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseMoveCommandChanged)));
private static void MouseMoveCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseMove += element_MouseMove;
}
private static void element_MouseMove(object sender, MouseEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseMoveCommand(element);
command.Execute(e);
}
public static void SetMouseMoveCommand(UIElement element, ICommand value)
{
element.SetValue(MouseMoveCommandProperty, value);
}
public static ICommand GetMouseMoveCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseMoveCommandProperty);
}
}
答案 0 :(得分:2)
将此样式添加到资源:
defmodule Storage do
def start_link do
Agent.start_link(fn -> 10 end, name: __MODULE__)
end
def add_to(input) do
Agent.get_and_update(__MODULE__, fn (x) -> {x + input, x + input} end)
end
end
Storage.start_link
IO.inspect Storage.add_to(5) # => 15
IO.inspect Storage.add_to(5) # => 20
<强>更新强>
试试这个:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Command" Value="{Binding MyCommand}"/>
</Style>
</StackPanel.Resources>
<Button/>
<Button/>
<Button/>
</StackPanel>
更新2
我重新创建了您的确切场景,它对我来说非常适合。该命令已附加,并按预期在每个鼠标移动事件上执行。
<Style TargetType="Button">
<Setter Property="mybehaviours:MouseMoveBehaviour.MouseMoveCommand" Value="{Binding MyCommand}"/>
</Style>