如何将两个附加行为附加到一个XAML元素?

时间:2009-05-29 15:00:01

标签: wpf mvvm attachedbehaviors

我已实施attached command behavior pattern found here效果良好以允许例如一个边框,用于在ViewModel中触发左键或右键单击事件:

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"
        >

2 个答案:

答案 0 :(得分:5)

您发送的链接包含了这个答案。您可以在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>

答案 1 :(得分:0)

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

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