我讀的MSDN動畫教程,它介紹了以下步驟將故事板應用於元素:如何使一個元素在XAML中引用的StaticResource故事板(而不是故事板引用元素)
- 創建故事板;
- 使用
TargetName
屬性指定其目標元素名稱; - (指定目標屬性);
- (添加一個事件觸發器來啓動動畫);
我看到一個概念性的問題,從中得出我的難處,那就是:
我有故事板和元件之間的一個一對一的關係,而這種關係在故事板定義。那麼,我如何創建一個Storyboard,並有條件地將它應用於多個元素,觸發動畫FROM ELEMENT ITSELF(通過綁定/觸發器,我想)。
我打算用例是mimmick LED的面板(橢圓的一個StackPanel),其中每個LED可以在四種邏輯狀態:開機,關機,快速閃爍,並緩慢閃爍(很像以太網路由器)。然後,我會創建動畫BlinkingSlow
和BlinkingFast
,然後在我的ViewModel進入相應的邏輯狀態時觸發該動畫。然後,我可以只關心ViewModel中的行爲,並讓View自己照顧自己,正確觸發並重用一些StaticResource Storyboard。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:blinking"
x:Class="blinking.MainWindow"
Title="MainWindow"
Background="{x:Null}"
WindowStartupLocation="CenterScreen">
<Window.Resources>
<System:Double x:Key="Diameter">40</System:Double>
<Color x:Key="RedOn">Red</Color>
<Color x:Key="RedOff">#FF570000</Color>
<Storyboard x:Key="BlinkSlow" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
Storyboard.TargetName="led4"
AutoReverse="True"
RepeatBehavior="Forever">
<DiscreteColorKeyFrame KeyTime="0" Value="{StaticResource RedOn}"/>
<DiscreteColorKeyFrame KeyTime="0:0:0.5" Value="{StaticResource RedOn}"/>
<EasingColorKeyFrame KeyTime="0:0:0.5" Value="{StaticResource RedOff}"/>
<DiscreteColorKeyFrame KeyTime="0:0:1" Value="{StaticResource RedOff}"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource BlinkSlow}"/>
</EventTrigger>
</Window.Triggers>
<StackPanel x:Name="leds_container" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,20,4,0">
<Ellipse x:Name="led1" Width="{StaticResource Diameter}" Height="{StaticResource Diameter}" Fill="#FFF90F0F" Margin="20,0,0,0"/>
<Ellipse x:Name="led2" Width="{StaticResource Diameter}" Height="{StaticResource Diameter}" Fill="#FFF90F0F" Margin="20,0,0,0"/>
<Ellipse x:Name="led3" Width="{StaticResource Diameter}" Height="{StaticResource Diameter}" Fill="#FFF90F0F" Margin="20,0,0,0"/>
<Ellipse x:Name="led4" Width="{StaticResource Diameter}" Height="{StaticResource Diameter}" Fill="#FFF90F0F" Margin="20,0,0,0"/>
</StackPanel>
</Window>
有什麼建議嗎?
要去給它一個嘗試,看起來像一個很好的解決方案,我只要一有新的信息,我會給予反饋,謝謝! – heltonbiker 2013-04-23 16:13:00
你介意如何實現我的ViewModel(用作DataContext)嗎?假設我有我的LedsPanelViewModel,名爲「State」的屬性,我應該如何設置這個屬性?像這樣的字符串'this.State =「BlinkSlowState」'例如,或者我應該創建一個枚舉?我很困惑... – heltonbiker 2013-04-23 16:36:25
我做到了,並且它的'Value'屬性是一個字符串。非常感謝你!! – heltonbiker 2013-04-23 17:10:24