gpt4 book ai didi

wpf - 如何在 UIElement 上重置 DesiredSize

转载 作者:行者123 更新时间:2023-12-03 21:01:15 26 4
gpt4 key购买 nike

我有一个列表框,其中包含任意数量的 UIElement s 大小未知。

我希望能够在添加每个项目后跟踪列表框的建议大小。这将允许我将一个大列表(例如:100 个项目)拆分为几个(例如:10)个大致相同的较小列表 视觉大小,而不管列表中每个元素的视觉大小。

但是,似乎 Measure pass 只影响 ListBoxDesiredSize第一次调用 Measure 时的属性:

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));

关于wpf - 如何在 UIElement 上重置 DesiredSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6065400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com