내 첫번째 생각은 이런 식으로 일할 수있는 것이 었습니다 :
<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
속성이 첫 번째 컨트롤로 설정되기 때문입니다.
나는이 해결책을 찾아왔다. - 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>
행동이 스타일 세터 내부에서 제대로 작동하지 않습니다 [의
가능한 중복 ] (https://stackoverflow.com/questions/27715798/behaviors-are-not-working-properly-inside-style-setter) – Artemious
이 질문에 대한 답변은 이미 있습니다. https://stackoverflow.com/a/29808226/1830814 – Artemious