繁体   English   中英

StackPanel SizeChanged事件

[英]StackPanel SizeChanged event

我已将此事件添加到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中检索项目的大小,我尝试了所有Size / Height属性,但没有一个能代表这一点:

            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());

我认为在您的情况下,您需要使用作为数据源使用ObservableCollection ListBox ,例如: 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添加时动画但不滚动

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM