StoryBoard - 从代码隐藏中设置目标名称

时间:2011-03-14 15:51:46

标签: c# wpf storyboard

我在资源中有StoryBoard

  <Window.Resources>
    <Storyboard x:Key="Fading" Storyboard.TargetName="NotifyWindow" Storyboard.TargetProperty="Opacity" >
        <DoubleAnimation From="1" To="0" Duration="0:0:1">
        </DoubleAnimation>
    </Storyboard>
  </Window.Resources>

在WindowClosing上我有下一个代码

private void NotifyWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    Storyboard fading = this.Resources["Fading"] as Storyboard;
    if (fading != null && !fadingCompleted)
    {
        fading.Completed += FadingStoryBoard_Completed;
        fading.Begin();
        e.Cancel = true;
    }
}

private void FadingStoryBoard_Completed(object sender, EventArgs e)
{
   fadingCompleted = true;
   Close();
   fadingCompleted = false;
}

这很好用,但我想将这个故事板移动到另一个程序集。所以我需要指定StoryBoard.TargetName表单代码。我怎么能这样做?

2 个答案:

答案 0 :(得分:18)

可以通过名为"Set" + PropertyName

的静态帮助方法从代码设置附加属性

参见C#示例here

Storyboard.SetTargetName(yourAnimation, "NotifyWindow"); 

答案 1 :(得分:8)

将依赖项属性设置为依赖项对象的标准方法与附加属性相同:

dependencyObjectInstance.SetValue(SampleClass.PropertyName + "Property", value);

在你的例子中:

fading.SetValue(Storyboard.TargetNameProperty, "NotifyWindow");