動的な特定プロパティ変化アニメーションの作成
xamlの中でターゲットのプロパティを表現するものをコードで指し示すにはPropertyPathを使うとよい。以下はOpacityを使って徐々に可視化するアニメーションをC#で記述する例。
相当するxaml
<Storyboard x:Key="DoShow"> <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="{x:Null}" Storyboard.TargetProperty="(UIElement.Opacity)"> <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/> <SplineDoubleKeyFrame KeyTime="00:00:01" Value="1"/> </DoubleAnimationUsingKeyFrames> </Storyboard>
C#でtargetを動的に指定
private void ShowByPhantomEffect(UIElement target) { const string TempName = "__ShowByPhantomEffectTarget__"; // x:Nameが設定されていない場合にも対応 RegisterName(TempName, target); DoubleAnimationUsingKeyFrames keyFrames = new DoubleAnimationUsingKeyFrames(); keyFrames.SetValue(Storyboard.TargetNameProperty, TempName); // PropertyPathに包んであげればOK keyFrames.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath(UIElement.OpacityProperty)); keyFrames.KeyFrames.Add(new SplineDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)))); keyFrames.KeyFrames.Add(new SplineDoubleKeyFrame(1, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1)))); Storyboard storyboard = new Storyboard(); storyboard.Children.Add(keyFrames); storyboard.Completed += delegate { UnregisterName(TempName); }; BeginStoryboard(storyboard); }
いくつものtargetを同時に扱う場合はTempNameをユニーク化する必要あり。