我的第一个想法是它可以这样工作:
<Style TargetType="Button">
<Setter Property="i:Interaction.Behaviors">
<Setter.Value>
<i:BehaviorCollection>
<core:EventTriggerBehavior EventName="Click">
<core:InvokeCommandAction Command="{Binding TestCommand}" />
</core:EventTriggerBehavior>
</i:BehaviorCollection>
</Setter.Value>
</Setter>
</Style>
但不幸的是,这只适用于获得附加行为的第一个控件。原因是该值只构造了一次,而BehaviorCollection 的AssociatedObject 属性设置为第一个控件。
然后我提出了这个解决方案 - How to add a Blend Behavior in a Style Setter 。
这个想法是创建一个附加属性,手动将行为分配给控件。
基于此,我建议你这样做:
public static class ListViewBehaviorAttacher
{
public static readonly DependencyProperty IsAttachedProperty = DependencyProperty.RegisterAttached(
"IsAttached", typeof( bool ), typeof( ListViewBehaviorAttacher ), new PropertyMetadata( default( bool ), IsAttachedChanged ) );
private static void IsAttachedChanged( DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs )
{
var listView = ( ListView )dependencyObject;
//create the binding
BehaviorCollection collection = new BehaviorCollection();
var eventTrigger = new EventTriggerBehavior() { EventName = "ItemClick" };
var invokeCommandAction = new InvokeCommandAction();
//binding to command
BindingOperations.SetBinding(
invokeCommandAction,
InvokeCommandAction.CommandProperty,
new Binding() { Path = new PropertyPath( "ShowItemClickedCommand" ), Source = listView.DataContext } );
eventTrigger.Actions.Add( invokeCommandAction );
collection.Add( eventTrigger );
listView.SetValue( Interaction.BehaviorsProperty, collection );
}
public static void SetIsAttached( DependencyObject element, bool value )
{
element.SetValue( IsAttachedProperty, value );
}
public static bool GetIsAttached( DependencyObject element )
{
return ( bool )element.GetValue( IsAttachedProperty );
}
}
然后在样式中像这样附加它:
<Style TargetType="ListView">
<Setter Property="SelectionMode" Value="None"></Setter>
<Setter Property="IsItemClickEnabled" Value="True" />
<Setter Property="local:ListViewBehaviorAttacher.IsAttached" Value="True" />
</Style>