[英]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.