2011-12-29 87 views
6

我正在嘗試使用Measure方法得到MyUserControl的實際大小之前類的建議爲我的previous question。但它不起作用。 MyUserControl有一個ItemsControl,它的數據綁定是List,如下所示。通過uc.MyCollection = myCollection;添加的項目未反映在uc.DesiredSize.Height中。在呈現之前獲取用戶控件的實際大小

MyUserControl uc= new MyUserControl(); 
uc.AName = "a1"; 
uc.Width = 194; 
uc.MyCollection = myCollection; //myCollection is a List databound to ItemsControl inside MyUserControl 
uc.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); 
uc.Arrange(new Rect(0, 0, uc.DesiredSize.Width, uc.DesiredSize.Width)); //Needed? 
uc.UCHeight = uc.DesiredSize.Height; //size of items databound to ItemsControl not reflected here 
uc.UCWidth = uc.DesiredSize.Width; 
uc.Margin = new Thickness(34, 42, 0, 0); 
myRoot.Children.Add(uc); //myRoot is Canvas 
+3

嘗試在調用'Mesaure()'之前在根上添加'uc'並在訪問'DesiredSize'之前執行'UpdateLayout()'。那就是我通常所做的。 – kev 2011-12-29 08:31:51

+0

這不起作用。 – devnull 2011-12-29 08:37:19

+0

@neutrino:什麼不工作?值是。 0還是不準確? – Tigran 2011-12-29 08:59:32

回答

6

您必須在您的uc中覆蓋MeasureOverride和ArrangeOverride來計算您自己的尺寸。在MeasureOverride內部「詢問」你的列表時,你可以使用它自己的大小「測量」 - 這樣你就可以計算出你自己的uc的大小(在MeasureOverride中返回這個大小) - 然後在調用uc.Measure之後得到你的DesiredSize。

+2

我很確定你只需要在自定義面板實現上實現這些方法。 UC只是其他控件的組合,所以沒有必要實現這些。 – ColinE 2011-12-29 16:28:53

+0

如果用戶控件具有綁定到List的'ItemsControl',該怎麼辦?在創建usercontrol之後,我設置了將'UserControl'的ItemsControl綁定到的'List'屬性。問題在於,usercontrol上的'Measure'調用返回'DesiredSize.Height'而不考慮ItemsControl的高度。 – devnull 2011-12-29 16:54:37

1

你的ItemsControl綁定到MyCollection的不會處理,直到你的用戶控件中的VisualTree,所以在你打電話措施來看,desiredsize仍爲0

當我需要一個FrameworkElement的大小,我將它的Opacity設置爲0,將其添加到可視化樹中,然後等待SizeChanged事件。

相關問題