如何在UIElement上重置DesiredSize

| 我有一个列表框,其中包含任意数量的size0ѭ,其大小未知。 我希望能够在添加每个项目后跟踪列表框的建议大小。这将使我可以将一个大列表(例如100个项目)分成几个(例如10个)视觉大小大致相同的较小列表,而不管列表中每个元素的视觉大小如何。 但是,在第一次调用Measure时,似乎Measure传递仅影响
ListBox
\的
DesiredSize
属性:
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\");
    }
}
我尝试将呼叫添加到:
listBox.InvalidateMeasure();
在添加项目之间无济于事。 是否有一种简单的方法可以在添加项目时计算出所需的
ListBox
(或任何
ItemsControl
)大小?     
已邀请:
如果将相同的大小传递给Measure方法,则在测量阶段将进行一些优化,以“重用”先前的测量。 您可以尝试使用不同的值以确保真正重新计算了度量,如下所示:
// 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));
    

要回复问题请先登录注册