C# StackPanel SizeChanged事件

C# StackPanel SizeChanged事件,c#,wpf,animation,stackpanel,C#,Wpf,Animation,Stackpanel,我已将此事件添加到StackPanel,以便在向StackPanel添加新项目时显示漂亮的动画: expandableStack.SizeChanged += (s, e) => { DoubleAnimation expand = new DoubleAnimation(); expand.Duration = TimeSpan.FromMilliseconds(250); expand.From

我已将此事件添加到StackPanel,以便在向StackPanel添加新项目时显示漂亮的动画:

 expandableStack.SizeChanged += (s, e) =>
        {
            DoubleAnimation expand = new DoubleAnimation();
            expand.Duration = TimeSpan.FromMilliseconds(250);
            expand.From = e.PreviousSize.Height;
            expand.To = e.NewSize.Height;
            expandableStack.BeginAnimation(HeightProperty, expand);
        };
如果新的大小比前一个更大,则效果很好,但是如果它更小(当我删除项目时),StackPanel不会更改其大小,因此不会触发事件SizeChanged

如何使StackPanel适应内容?或者,如何在StackPanel中检索项目的大小,我尝试了所有大小/高度属性,但没有一个表示:

            MessageBox.Show("Height: " + expandableStack.Height.ToString());
            MessageBox.Show("ActualHeight: " + expandableStack.ActualHeight.ToString());
            MessageBox.Show("Render size: " + expandableStack.RenderSize.Height.ToString());
            MessageBox.Show("ViewportHeight size: " + expandableStack.ViewportHeight.ToString());
            MessageBox.Show("DesiredSize.Height size: " + expandableStack.DesiredSize.Height.ToString());
            MessageBox.Show("ExtentHeight size: " + expandableStack.ExtentHeight.ToString());
            MessageBox.Show("VerticalOffset size: " + expandableStack.VerticalOffset.ToString());

我认为在您的情况下,您需要使用一个控件作为数据源使用
可观察集合
,例如:
ItemsControl
ListBox
,因为它是一个事件
CollectionChanged
,其中包含对集合[]执行的行为的枚举:

此事件将按如下方式实施:

// Set the ItemsSource
SampleListBox.ItemsSource = SomeListBoxCollection;

// Set handler on the collection
SomeListBoxCollection.CollectionChanged += new NotifyCollectionChangedEventHandler(SomeListBoxCollection_CollectionChanged);

private void SomeListBoxCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        // Some actions, in our case - start the animation
    }
}
有关添加动画元素的更详细示例(在
列表框中),请参见我的答案:

列表框
元素可以是任何类型的
控件
元素

// Set the ItemsSource
SampleListBox.ItemsSource = SomeListBoxCollection;

// Set handler on the collection
SomeListBoxCollection.CollectionChanged += new NotifyCollectionChangedEventHandler(SomeListBoxCollection_CollectionChanged);

private void SomeListBoxCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Add)
    {
        // Some actions, in our case - start the animation
    }
}