StackPanel SizeChanged事件

时间:2013-07-14 20:37:32

标签: c# wpf animation stackpanel

我将这个事件添加到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());

1 个答案:

答案 0 :(得分:1)

我认为在您的情况下,您需要使用一个控件作为数据源使用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 DataBound ListBox Animate on Add but not Scroll

ListBox元素可以是任何类型的Control元素。