如何解决MeasureOverride方法未设置Panel的期望大小
| 我创建了一个名为LinearLayout的新面板,并且管理布局时遇到问题,因为在调用MeasureOverride方法后未设置期望的字段...这是我的代码: protected override Size MeasureOverride(Size availableSize)
{
Size panelDesiredSize = new Size();
if ((this.widthWrap) || (this.heightWrap))
{
foreach (UIElement elemento in this.Children)
{
System.Diagnostics.Debug.WriteLine(\"Measure\" + ((FrameworkElement)elemento).Name);
((FrameworkElement)elemento).Measure(new Size(((FrameworkElement)elemento).Width,((FrameworkElement)elemento).Height));
System.Diagnostics.Debug.WriteLine(\" child this desireddSIze\" + ((FrameworkElement)elemento).DesiredSize);
if (this.Orientation.Equals(System.Windows.Controls.Orientation.Vertical))
{
if (this.widthWrap)
{
//the widest element will determine containers width
if (panelDesiredSize.Width < ((FrameworkElement)elemento).Width)
panelDesiredSize.Width = ((FrameworkElement)elemento).Width;
}
//the height of the Layout is determine by the sum of all the elment that it cointains
if (this.heightWrap)
panelDesiredSize.Height += ((FrameworkElement)elemento).Height;
}
else
{
if (this.heightWrap)
{
//The highest will determine the height of the Layout
if (panelDesiredSize.Height < ((FrameworkElement)elemento).Height)
panelDesiredSize.Height = ((FrameworkElement)elemento).Height;
}
//The width of the container is the sum of all the elements widths
if (this.widthWrap)
panelDesiredSize.Width += ((FrameworkElement)elemento).DesiredSize.Width;
}
}
}
return panelDesiredSize;
}
我嵌套两个线性布局:L1是L2的父级,L2是3个按钮的父级。
有趣的是,如果我在LinearLayout类中的任何位置下面编写代码,它将起作用,并且再次调用Layout机制,并且可以正常工作。 ansrangingoverride不被调用)
this.Width = finalSize.Width;
this.Height = finalSize.Height;
这是一个错误吗?还是只是我???我已经待了两天了,对其他人来说似乎很奏效...
如果有人可以帮助我,我将非常感谢!
顺便说一下,我正在使用Silverlight for Windows Phone 7 ...
解决方法
测量阶段将设置DesiredSize属性,而不是Width / Height属性。 Width / Height属性用于为元素提供明确的尺寸,而不是自动适应其内容(即通过MeasureOverride)。
您不应基于度量或布置阶段的结果来设置宽度/高度,因为度量和布置阶段会使用这些属性来确定最佳尺寸。
UpdateLayout并不是要强制元素重新测量/重新排列自身。您将需要为该任务使用InvalidateMeasure或InvalidateArrange。
编辑:
另外,这行代码不是真的正确:
((FrameworkElement)elemento).Measure(new Size(((FrameworkElement)elemento).Width,((FrameworkElement)elemento).Height));
您应该传递availableSize或面板要给元素的任何大小。宽度/高度可能不是有效的尺寸。
一般的经验法则是您的面板不应触摸Width / Height / MinWidth / MinHeight / etc类型的属性。它应该只是根据给定的可用大小传入一个可用大小。或者,您可以在安排元素所需的空间时传递new Size(double.PositiveInfinity,double.PositiveInfinity)
。
在您的安排阶段,您可以使用element.DesiredSize来确定元素的安排。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。