0

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

1 回答 1

1

我认为在您的情况下,您需要使用作为数据源的控件,ObservableCollection例如:ItemsControl、、ListBox等。因为它是一个事件 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 动画添加但不滚动

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

于 2013-07-15T06:42:56.703 回答