使用样式应用多个AttachedCommandBehaviors

时间:2012-03-15 22:58:17

标签: c# wpf mvvm mvvm-light

我正在尝试使用AttachedCommandBehavior V2将ListBoxItem事件(例如双击)转换为针对视图模型执行的命令。

我想为多个事件触发命令,这是我试图模拟的示例代码:

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

因为我想将它应用于ListBoxItem,所以我试图通过样式来实现:

<ListBox.ItemContainerStyle>
    <Style>
        <Setter Property="acb:CommandBehaviorCollection.Behaviors">
            <Setter.Value>
                <acb:CommandBehaviorCollection>
                    <acb:BehaviorBinding Event="MouseDoubleClick" Command="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"/>
                    <acb:BehaviorBinding Event="KeyUp" Command="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"/>
                </acb:CommandBehaviorCollection>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

但是我的代码显示error MC3089: The object 'CommandBehaviorCollection' already has a child and cannot add 'BehaviorBinding'. 'CommandBehaviorCollection' can accept only one child. Line 39 Position 11.

时出现编译错误

此外,如果我注释掉其中一个BehaviorBindings然后它编译,但我得到一个运行时xaml加载异常,说“值不能为null。参数名称:属性”,所以我不确定我是否采取了正确的方法

任何人都可以提供一个正确的语法示例,以便在ListBoxItem上设置多个行为绑定吗?

1 个答案:

答案 0 :(得分:1)

我的解决方案使用交互触发器和ItemTemplate而不是ItemContainerStyle。 这将在文本框中调用鼠标双击或键盘命令,而不是整个列表框项。

<UserControl.Resources>
    <DataTemplate DataType="{x:Type ViewModel:DataItem}" x:Key="ItemTemplate">
        <ContentControl>
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseDoubleClick">
                    <i:InvokeCommandAction Command="{Binding DoubleClickCommand}"/>
                </i:EventTrigger>
                <i:EventTrigger EventName="KeyUp">
                    <i:InvokeCommandAction Command="{Binding KeyUpCommand}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <TextBox Text="{Binding Name}">
            </TextBox>
        </ContentControl>
    </DataTemplate>
</UserControl.Resources>

<ListBox x:Name="listBox" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource={Binding Items} />

DataItem就像

class DataItem : INotifyPropertyChanged
{
   public string Name{get;set}
   .. etc
}

并且DataContext上设置的视图模型具有IList<DataItems> Items{get; private set}属性。