簡體   English   中英

在WPF中ItemsControl的DataContext更改時動畫高度更改

[英]Animate height change when the DataContext of an ItemsControl changes in WPF

我有一個綁定到其DataContextItemsControl DataContext更改時,我希望ItemsControl的高度更改動畫化。 我試圖為ItemsControl指定一個DataContextChanged事件:

<ItemsControl x:Name="items" ItemsSource="{Binding}" ItemTemplate="{StaticResource LocationTemplate}" DataContextChanged="Items_DataContextChanged">

在處理程序中,我嘗試為高度創建DoubleAnimation 但是,我不知道如何指定FromTo屬性。 有人可以幫忙嗎? 謝謝!

通過將ItemsControl包裝在Canvas我能夠創造出您想要的效果(我認為):

<Canvas x:Name="ClippingContainer" Background="Aquamarine" HorizontalAlignment="Center" VerticalAlignment="Center" ClipToBounds="True">
    <ItemsControl x:Name="ICont" ItemsSource="{Binding}" SizeChanged="ItemsControl_SizeChanged"/>
</Canvas>

然后通過設置父級CanvasHeightWidth屬性的動畫來響應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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM