기본 Viewmodel이 지시할 때 View 트리거에 WPF EventTrigger를 어떻게 둘 수 있습니까?
-
07-07-2019 - |
문제
시나리오는 다음과 같습니다.
다음과 같은 사용자 컨트롤이 있습니다. 뷰 모델이 "발광 활성화"가 필요하다는 신호를 뷰에 알려 스토리보드를 재생할 수 있어야 한다는 아이디어입니다.
<UserControl x:Class="View.UnitView" ... >
...
<Storyboard x:Key="ActivateGlow">
...
</Storyboard>
...
<!-- INVALID BINDING! Not Dependancy Object-->
<EventTrigger RoutedEvent="{Binding OnActivateGlow}">
<BeginStoryboard Storyboard="{StaticResource ActivateGlow}"/>
</EventTrigger>
</UserControl>
UnitView의 코드 숨김에는 다음이 있습니다.
public event EventHandler ActivateGlow;
MVVM에서는 매우 일반적인 것처럼 UnitViewModel에 대해 다음과 같은 DataTemplate이 있습니다.
<DataTemplate DataType="{x:Type vm:UnitViewModel}">
<vw:UnitView d:DesignWidth="150" d:DesignHeight="100" />
</DataTemplate>
궁극적인 질문은 뷰모델이 OnActivateGlow 이벤트를 실행할 수 있도록 어떻게 설정해야 하느냐는 것입니다.
해결책
업데이트:Firoso는 의견에서 언급했듯이 (내 생각에는 – 즉테스트되지 않음) 요구 사항을 충족하기 위해 혼합 동작 구성 요소를 사용할 수 있습니다.
SDK를 다운로드하고 설치하는 것 외에도.표현식 혼합 샘플 라이브러리의 사본을 얻으세요(다음 링크에서 다운로드를 클릭해야 합니다):Expression Blend 샘플
이 라이브러리에는 뷰 모델에 선언된 이벤트에 대한 응답으로 작업을 트리거하는 데 사용할 수 있는 'DataEventTrigger'라는 사전 구축된 트리거가 포함되어 있습니다.
Blend SDK에는 이미 퍼즐의 다른 부분이 있습니다. 즉, 스토리보드를 제어할 수 있는 작업이 이미 포함되어 있습니다.이 액션의 이름은 'ControlStoryboardAction'입니다.
다음과 같은 xaml로 끝나야 합니다.
<i:Interaction.Triggers>
<samples:DataEventTrigger EventName="YourEvent">
<im:ControlStoryboardAction Storyboard="{StaticResource Storyboard1}"
ControlStoryboardOption="Play"/>
</samples:DataEventTrigger>
</i:Interaction.Triggers>
'YourEvent'를 뷰 모델에 정의한 이벤트 이름으로 바꾸고 'Storyboard1'을 스토리보드 이름으로 바꾸세요.물론 이름은 정확히 일치해야 합니다.
사용된 xaml 네임스페이스 정의는 다음과 같습니다.
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:im="clr-namespace:Microsoft.Expression.Interactivity.Media;assembly=Microsoft.Expression.Interactions"
xmlns:samples="clr-namespace:Expression.Samples.Interactivity;assembly=Expression.Samples.Interactivity"
편집 전 원본 게시물:
Expression Blend 동작을 살펴볼 것을 제안합니다.
다른 팁
뷰 모델에 부울 isglowing 속성을 넣고 스타일에 Datatriggers를 사용할 수 있습니다.
<Rectangle.Style>
<Style TargetType="{x:Type Rectangle}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsGlowing}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
...
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
나는 당신이 a에 묶어야한다고 믿습니다 RoutedEvent
CLR 이벤트가 아닙니다.
나는 그것을 시도하지 않았지만 이와 같은 것이 효과가 있어야합니다.
public class UnitView
{
public static readonly RoutedEvent ActivateGlowEvent
= EventManager.RegisterRoutedEvent(
"ActivateGlow", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(UnitView)
);
public void RaiseActivateGlowEvent()
{
RaiseEvent(new RoutedEventArgs(ActivateGlowEvent));
}
}
이것을 해결하는 한 가지 방법은 위의 컨트롤이 포함 된 데이터 템플릿에서 데이터 트리거를 사용하는 것입니다. 아마도이를 수행하는 가장 좋은 방법은 아닙니다. 나는 여전히 더 나은 아이디어에 열려 있습니다.