你在我的主Grid和PanelTemplate中有ItemsControl作为wrapPanel。在这个wrapPanel中我放了MyCustomControl。我想动态设置MycustomControl的宽度。此外,我需要在MyCustomControl的onLoaded事件中访问此宽度。有人可以帮忙吗?
答案 0 :(得分:0)
我假设您要将自定义控件(MyCustomControl)放入可视容器(在本例中为WrapPanel)。
我发现在OnLoaded事件中查找ActualWidth和ActualHeight属性不起作用,因为Silverlight中的布局过程尚未完成。
每个可视容器都实现一个两阶段流程,负责调整和安排其子控件。
举一个例子,这是一个实现刚才提到的两阶段过程的面板类(MeasureOverride()和ArrangeOverride())。
public class RowPanel : Panel
{
private const double _groupSpace = 80;
public Point Location;
public RowPanel ()
: base()
{
Location = new Point();
}
protected override Size MeasureOverride ( Size availableSize )
{
Size size = new Size( double.PositiveInfinity, double.PositiveInfinity );
foreach ( UIElement child in Children )
child.Measure( size );
return this.ArrangeNodes( false );
}
protected override Size ArrangeOverride ( Size finalSize )
{
return this.ArrangeNodes( true );
}
private Size ArrangeNodes ( bool arrange )
{
double pos = 0d;
Rect bounds = new Rect();
Size totalSize = new Size( 0, 0 );
foreach ( UIElement child in Children )
{
GroupPanel group = child as GroupPanel;
bounds.X = pos;
bounds.Y = 0;
bounds.Width = group.DesiredSize.Width;
bounds.Height = group.DesiredSize.Height;
if ( arrange )
{
group.Arrange( bounds );
Point b = new Point( bounds.X, bounds.Y );
group.SetValue( GroupPanel.LocationProperty, b );
}
totalSize.Width = pos + group.DesiredSize.Width;
totalSize.Height = Math.Max( totalSize.Height, group.DesiredSize.Height );
pos += ( bounds.Width + RowPanel._groupSpace );
}
return totalSize;
}
}
我建议您为可视容器和自定义控件实现MeasureOverride和ArrangeOverride。