StackPanel SizeChanged event

本文关键字:event SizeChanged StackPanel | 更新日期: 2023-09-27 18:22:28

我已经将此事件添加到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());

StackPanel SizeChanged event

我认为在您的情况下,您需要使用一个作为数据源使用ObservableCollection的控件,例如:ItemsControlListBox等。因为它是一个事件CollectionChanged,在中包含对集合执行的操作的枚举[MSDN]:

Member name   Description
------------  ------------
Add           One or more items were added to the collection.
Move          One or more items were moved within the collection.
Remove        One or more items were removed from the collection.
Replace       One or more items were replaced in the collection.
Reset         The content of the collection changed dramatically.

此事件的实施方式如下:

// 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
    }
}

添加动画元素的更详细示例(在ListBox中),请参阅我的答案:

WPF数据绑定列表框在添加但不滚动时动画

CCD_ 6元素可以是任何类型的CCD_。