4
我有一個列表框,其中包含大小未知的任意數量的UIElement
。如何重置UIElement上的DesiredSize
我希望能夠在添加每個項目後跟蹤建議的列表框大小。這將允許我將大型列表(例如:100個項目)分成幾個(如:10個)較小的列表,其大小几乎相同,不管列表中每個元素的可視大小如何。
然而,似乎一個測量通隻影響在第一次調用的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
)的期望大小?
謝謝你,這個工作。你知道是否有辦法關閉這個「優化」? – Michael 2011-05-20 14:14:30
@米克 - 不,對不起。我從未找到另一種解決方案。 – CodeNaked 2011-05-20 14:21:07