我有一个带有UserControls的StackPanel作为孩子。我想应用一个Storyboard动画,它可以在一秒钟内将孩子的高度从0增加到100,从而创建一个平滑的向下滑动动画。将新子项添加到StackPanel - StackPanel1.children.Add(usercontrol1)
时将调用此方法。 StackPanel子项是UserControls所以我不想要使用DataTemplates。下面是我的意思的布局示例。
有人可以帮助我创建这个,因为我不知道如何制作它。谢谢。
答案 0 :(得分:2)
您需要定位StoryBoard的对象。
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));
// **Set the Target Object for the Animation.**
Storyboard.SetTarget(myDoubleAnimation, usercontrol1);
// Create a storyboard to contain the animation.
Storyboard myWidthAnimatedButtonStoryboard = new Storyboard();
myWidthAnimatedButtonStoryboard.Children.Add(myDoubleAnimation);
myWidthAnimatedButtonStoryboard.Begin(usercontrol1);
}
答案 1 :(得分:1)
嗯,这或多或少是上面评论中所写链接的复制粘贴。 首先,您需要创建您的控件(比如说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);
}