2011-12-29 92 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事件。

相关问题