【问题标题】:StackPanel SizeChanged eventStackPanel SizeChanged 事件
【发布时间】:2013-07-16 00:32:51
【问题描述】:

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

【问题讨论】:

    标签: c# wpf animation stackpanel


    【解决方案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 元素。

    【讨论】:

      猜你喜欢
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 2013-10-07
      相关资源
      最近更新 更多