我目前遇到了问题。我想为我的所有列表视图声明一个eventriggerbehavior。这是我的代码:
<Style TargetType="ListView">
<Setter Property="ItemTemplate" Value="{StaticResource itemShowTemplate}" />
<i:Interaction.Behaviors>
<Interactions:EventTriggerBehavior EventName="ItemClicked">
<Interactions:InvokeCommandAction Command="{Binding ShowItemClickedCommand}" />
</Interactions:EventTriggerBehavior>
</i:Interaction.Behaviors>
</Style>
我现在遇到的问题是EventTriggerBehavior正在寻找Style上的事件而不是Listview的目标类型。而在EventTriggerBehavior上设置的唯一属性是SourceObject。但是我不希望在1个列表视图中出现这种行为,我希望它在我的列表视图中。
有没有办法解决这个问题?
答案 0 :(得分:1)
我的第一个想法是它可以这样工作:
<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>
但不幸的是,这仅适用于第一个获得附加行为的控件。原因是该值只构造一次,AssociatedObject
的{{1}}属性设置为第一个控件。
然后我接受了这个解决方案 - How to add a Blend Behavior in a Style Setter。 我们的想法是创建一个附加属性,手动将行为分配给控件。
基于此,我建议你这样做:
BehaviorCollection
然后在风格中附上它:
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 );
}
}