I've added this event to a StackPanel for displaying a nice animation when I add new items to the 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);
};
It works nice if the new size is greater that the previous, but if it is smaller (when I delete the items) the StackPanel does not change its size, and therefore the event SizeChanged is not firing.
How could I make the StackPanel adjust to the content? Or, how could I retrieve the size of my items inside the StackPanel, I've tried all Size/Height properties and none of them represent that:
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());
I think in your situation you need to use a control that as a data source uses a ObservableCollection
, for example: ItemsControl
, ListBox
, etc. Because it is an event CollectionChanged
, in that contains the enumeration of acts performed on the collection [ 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.
This event will be implemented like this:
// 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
}
}
A more detailed example of adding an element of animation (in ListBox
), see my answer:
WPF DataBound ListBox Animate on Add but not Scroll
ListBox
element can be any type of Control
element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.