Mic*_*ael 5 size wpf listbox itemscontrol uielement
我有一个包含任意数量的列表框 UIElement大小未知s。
我希望能够在添加每个项目后跟踪列表框的建议大小。这将允许我将一个大列表(例如: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");
}
}
Run Code Online (Sandbox Code Playgroud)
我曾尝试添加一个呼叫:
listBox.InvalidateMeasure();
Run Code Online (Sandbox Code Playgroud)
在添加项目之间无济于事。
是否有一种简单的方法可以在添加项目时计算 a 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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1564 次 |
| 最近记录: |