2011-05-19 59 views
4

我有一個列表框,其中包含大小未知的任意數量的UIElement如何重置UIElement上的DesiredSize

我希望能夠在添加每個項目後跟蹤建議的列表框大小。這將允許我將大型列表(例如:100個項目)分成幾個(如:10個)較小的列表,其大小几乎相同,不管列表中每個元素的可視大小如何。

然而,似乎一個測量通隻影響在第一次調用的ListBoxDesiredSize財產來衡量:

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)的期望大小?

回答

3

在測量階段有一些優化,如果將相同的尺寸傳遞給測量方法,將「重複使用」以前的測量。

您可以嘗試使用不同的值,以確保測量是真正的重新計算,像這樣:

// 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)); 
+0

謝謝你,這個工作。你知道是否有辦法關閉這個「優化」? – Michael 2011-05-20 14:14:30

+0

@米克 - 不,對不起。我從未找到另一種解決方案。 – CodeNaked 2011-05-20 14:21:07