在WPF上的多个UIElements上应用相同的命令

时间:2015-08-06 18:18:12

标签: wpf data-binding command

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);
    }
}

1 个答案:

答案 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>