繁体   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