一个ItemsControl)。用户控件动态添加到画布。我需要在渲染之前获取控件的实际大小(包括ItemsControl占用的空间)。我尝试覆盖UserControl的MeasureOverride方法,希望大小会反映在DesiredSize属性中。但它没有用。XAML是:我正在覆盖UserControl的MeasureOverride,如下所示:namespaceMyTools{publicpartialclassMyControl:UserControl{publicMyControl(){InitializeComponent();}publicstringControlName{得到;放;}公共对象MyItems{得到;放;}publicclassRow{publicstringMyVal{get;放;}}protectedoverrideSizeMeasureOverride(SizeavailableSize){vardesiredSize=base.MeasureOverride(availableSize);varsideLength=Math.Min(desiredSize.Width,desiredSize.Height);desiredSize.Width=sideLength;desiredSize.Height=sideLength;返回所需的大小;}}}客户代码:MyControlcontrol1=newMyControl();control1.ControlName="测试名称";vartest=newList(newMyControl.Row[]{newMyControl.Row{MyVal="Item1"},newMyControl.Row{MyVal="Item2"},newMyControl.Row{MyVal="Item3"}});control1.MyItems=测试;control1.Measure(newSize(double.PositiveInfinity,double.PositiveInfinity));消息框.Show(control1.DesiredSize.Height.ToString());canvas1.Children.Add(control1);我没有在客户端使用DesiredSize.Height属性获得实际大小关于如何解决这个问题的任何想法?您的用户控件是否定义为更改高度以反映内容的大小?默认情况下,您的用户控件将固定大小并且不会更改高度,因为项目控件具有更多条目。我认为您需要向网格添加用户控件,然后测量网格。这就是我测量控件的方式,它似乎工作正常,即使直接测量控件不像您的情况那样工作......MyControlcontrol1=newMyControl();...您的control1设置代码...将containerGrid调暗为新网格containerGrid.Children.Add(control1)containerGrid.Measure(NewSize(Double.MaxValue,Double.MaxValue))containerGrid.Arrange(NewRect(0,0,Double.MaxValue,Double.MaxValue))...现在检查grid.ActualWidth和grid.ActualHeight尝试使用ActualWidth和ActualHeight属性。以上就是C#学习教程:HowtooverrideMeasureOverridetofindthesizeofItemsControl分享的所有内容,如果对大家有用还需要详细了解C#学习教程,希望大家多多关注——protectedoverrideSizeMeasureOverride(SizeavailableSize){vardesiredSize=newSize();varsideLength=Math.Min(ActualWidth,ActualHeight);desiredSize.Width=sideLength;desiredSize.Height=sideLength;返回所需的大小;联系管理员删除。如需转载请注明出处:
