好吧,这或多或少是上面评论中所写链接的复制粘贴。首先,您需要创建您的控件(假设是 usercontrol1)并给它一个唯一的名称,以便故事板引用它。
编辑:下面是一个简单的应用程序的代码:
XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="800"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Name="StackPanel1">
</StackPanel>
<Button Grid.Row="1" Click="Button_Click">
</Button>
</Grid>
和后面的代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
var usercontrol1 = new Label();
usercontrol1.Background = new SolidColorBrush(Colors.Red);
usercontrol1.Content = "Hello";
usercontrol1.Name = "UniqueName" + System.Guid.NewGuid().ToString("N");
RegisterName(usercontrol1.Name, usercontrol1);
StackPanel1.Children.Add(usercontrol1);
// Create a DoubleAnimation to animate the width of the button.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 0;
myDoubleAnimation.To = 100;
myDoubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(1000));
// Configure the animation to target the button's Width property.
Storyboard.SetTargetName(myDoubleAnimation, usercontrol1.Name);
Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Button.HeightProperty));
// Create a storyboard to contain the animation.
Storyboard myWidthAnimatedButtonStoryboard = new Storyboard();
myWidthAnimatedButtonStoryboard.Children.Add(myDoubleAnimation);
myWidthAnimatedButtonStoryboard.Begin(usercontrol1);
}