【问题标题】:How can I attach two attached behaviors to one XAML element?如何将两个附加行为附加到一个 XAML 元素?
【发布时间】:2009-05-29 15:00:00
【问题描述】:

我已经实现了 attached command behavior pattern found here 并且它运行良好以允许例如具有在 ViewModel 中触发的左键或右键单击事件的 Border:

XAML:

<Border Background="Yellow" Width="350" Margin="0,0,10,0" Height="35" CornerRadius="2"
        c:CommandBehavior.Event="MouseLeftButtonDown" 
        c:CommandBehavior.Command="{Binding PressedLeftButton}"
        c:CommandBehavior.CommandParameter="MainBorder123">
    <TextBlock Text="this is the click area"/>
</Border>

代码隐藏:

public ICommand PressedLeftButton { get; private set; }

public MainViewModel()
{

    Output = "original value";

    PressedLeftButton = new SimpleCommand
    {
        ExecuteDelegate = parameterValue => {
            Output = String.Format("left mouse button was pressed at {0} and sent the parameter value \"{1}\"", DateTime.Now.ToString(), parameterValue.ToString());
        }
    };
}

但是,如何将两个附加行为附加到一个元素,例如我想做类似以下的事情,但它当然会给我一个错误:

<Border Background="Yellow" Width="350" Margin="0,0,10,0" Height="35" CornerRadius="2"
        c:CommandBehavior.Event="MouseLeftButtonDown" 
        c:CommandBehavior.Command="{Binding PressedLeftButton}"
        c:CommandBehavior.CommandParameter="MainBorder123"
        c:CommandBehavior.Event="MouseRightButtonDown" 
        c:CommandBehavior.Command="{Binding PressedRighttButton}"
        c:CommandBehavior.CommandParameter="MainBorder123"
        >

【问题讨论】:

    标签: wpf mvvm attachedbehaviors


    【解决方案1】:

    您发送的链接包含该答案。您可以使用 ACB v2 中的 CommandBehaviorCollection.Behaviors 功能。

       <Border Background="Yellow" Width="350" Margin="0,0,10,0" Height="35" CornerRadius="2" x:Name="test">
           <local:CommandBehaviorCollection.Behaviors>
                   <local:BehaviorBinding Event="MouseLeftButtonDown" Action="{Binding DoSomething}" CommandParameter="An Action on MouseLeftButtonDown"/>
                   <local:BehaviorBinding Event="MouseRightButtonDown" Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/>
           </local:CommandBehaviorCollection.Behaviors>
           <TextBlock Text="MouseDown on this border to execute the command"/>
       </Border>
    

    【讨论】:

    • 就是这样,谢谢,有趣的是我的 XAML 编辑器给了我错误“在类型 'CommandBehaviorCollection' 中找不到可附加属性 'Behaviors'。”虽然我可以正常运行和编译,但这是为什么呢?
    【解决方案2】:

    “就是这样,谢谢,有趣的是我的 XAML 编辑器给了我错误“在类型 'CommandBehaviorCollection' 中找不到可附加属性 'Behaviors'。”虽然我可以运行和编译它,但这是为什么呢? "

    原因是允许命令行为集合(这是一个附加属性collection)的代码实际上是一种 XAML 漏洞。您可以在此处阅读更多相关信息: http://wekempf.spaces.live.com/blog/cns!D18C3EC06EA971CF!468.entry?sa=276442122

    【讨论】:

      猜你喜欢
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多