[英]Animate height change when the DataContext of an ItemsControl changes in WPF
我有一个绑定到其DataContext
的ItemsControl
。 当DataContext
更改时,我希望ItemsControl
的高度更改动画化。 我试图为ItemsControl
指定一个DataContextChanged
事件:
<ItemsControl x:Name="items" ItemsSource="{Binding}" ItemTemplate="{StaticResource LocationTemplate}" DataContextChanged="Items_DataContextChanged">
在处理程序中,我尝试为高度创建DoubleAnimation
。 但是,我不知道如何指定From
和To
属性。 有人可以帮忙吗? 谢谢!
通过将ItemsControl
包装在Canvas
我能够创造出您想要的效果(我认为):
<Canvas x:Name="ClippingContainer" Background="Aquamarine" HorizontalAlignment="Center" VerticalAlignment="Center" ClipToBounds="True">
<ItemsControl x:Name="ICont" ItemsSource="{Binding}" SizeChanged="ItemsControl_SizeChanged"/>
</Canvas>
然后通过设置父级Canvas
的Height
和Width
属性的动画来响应ItemsControl.SizeChanged
事件。
private void ItemsControl_SizeChanged(object sender, SizeChangedEventArgs e)
if (double.IsNaN(ClippingContainer.Height))
{
ClippingContainer.Height = e.NewSize.Height;
}
else
{
ClippingContainer.BeginAnimation(FrameworkElement.HeightProperty, new DoubleAnimation(e.NewSize.Height, new Duration(TimeSpan.FromSeconds(1))));
}
if (double.IsNaN(ClippingContainer.Width))
{
ClippingContainer.Width = e.NewSize.Width;
}
else
{
ClippingContainer.BeginAnimation(FrameworkElement.WidthProperty, new DoubleAnimation(e.NewSize.Width, new Duration(TimeSpan.FromSeconds(1))));
}
}
注意:这可以轻松转换为自己的UserControl
。 这样,您就可以覆盖MeasureOverride
并强制布局传递以重绘动画ItemsControl
所属的任何父布局容器。
我希望你觉得这有帮助。
private void MyItemsControl_DataContextChanged(object Sender, DependencyPropertyChangedEventArgs e)
{
BeginAnimation(HeightProperty, New DoubleAnimation(500.0, New Duration(Timespan.FromMilliseconds(500))));
}
private void Grid_SizeChanged_1(object sender, SizeChangedEventArgs e)
{
e.Handled = true;
BeginAnimation(HeightProperty, new System.Windows.Media.Animation.DoubleAnimation(e.NewSize.Height, new Duration(TimeSpan.FromSeconds(1))));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.