How to reset the desired size in a UIElement

I have a list box containing any number of UIElement whose size is unknown.

I want to track the suggested size of the list box after adding each item. This will allow me to split a large list (for example: 100 items) into several (more than 10) smaller lists of approximately the same visual size, regardless of the visual size of each item in the list.

However, it seems that the Measure pass only affects the ListBox DesiredSize property the first time Measure is called:

 public partial class TestWindow : Window { public TestWindow() { InitializeComponent(); ListBox listBox = new ListBox(); this.Content = listBox; // Add the first item listBox.Items.Add("a"); // Add an item (this may be a UIElement of random height) listBox.Measure(new Size(double.MaxValue, double.MaxValue)); // Measure the list box after the item has been added Size size1 = listBox.DesiredSize; // reference to the size the ListBox "wants" // Add the second item listBox.Items.Add("b"); // Add an item (this may be a UIElement of random height) listBox.Measure(new Size(double.MaxValue, double.MaxValue)); // Measure the list box after the item has been added Size size2 = listBox.DesiredSize; // reference to the size the ListBox "wants" // The two heights should have roughly a 1:2 ratio (width should be about the same) if (size1.Width == size2.Width && size1.Height == size2.Height) throw new ApplicationException("DesiredSize not updated"); } } 

I tried to add a call:

 listBox.InvalidateMeasure(); 

between adding items to no avail.

Is there an easy way to calculate the desired size of a ListBox (or any ItemsControl ) when adding time items?

+4
source share
1 answer

At the measurement stage, there are several optimizations that will β€œreuse” previous measurements if the same size is passed to the measurement method.

You can try using different values ​​to make sure that the measurement is really recalculated, for example:

 // Add the second item listBox.Items.Add("b"); // Add an item (this may be a UIElement of random height) listBox.Measure(new Size(1, 1)); listBox.Measure(new Size(double.MaxValue, double.MaxValue)); 
+3
source

All Articles