从资源中的故事板中为用户控件内的属性设置动画

时间:2012-01-10 09:16:34

标签: wpf user-controls storyboard

我有一个Resources.xaml文件,其中包含一个Storyboard,其目标是名为myButton的控件(此控件位于另一个用户控件中):

<ResourceDictionary ...>
  <Storyboard x:Key="expandWizard">
    <DoubleAnimation Storyboard.TargetName="myButton"
                     Storyboard.TargetProperty="Width"
                     To="200" Duration="0:0:0.250" />
  </Storyboard>
</ResourceDictionary>

资源字典在包含用户控件Shell.xaml的{​​{1}}文件中引用:

Test

最后,用户控件<Window xmlns:test="clr-namespace:MyProject.UI" ...> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Resources.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> <!-- User control that contains a button. --> <test:Test x:Name="testControl" /> </Window> 包含一个名为Test.xaml的按钮:

myButton

当我运行故事板时,我收到一个错误:<UserControl ...> <Button x:Name="myButton" Content="OK" /> </UserControl>

这是有道理的,因为InvalidOperationException: 'myButton' name cannot be found in the name scope of 'MyProject.UI.Shell'不是直接在myButton内,但我怎样才能使这项工作?

1 个答案:

答案 0 :(得分:3)

您应该能够直接在目标控件上运行Storyboard。假设您的UserControl名为testControl,那么您可以调用

Storyboard sb = (Storyboard)Resources["expandWizard"];
testControl.BeginStoryboard(sb);