0

我的 UserControl 中有一个带有自定义 UIElements 的 UIElementCollection。但不显示 UIElements。怎么了?

public partial class MyControl : UserControl
{
    public static readonly DependencyProperty ChildrenProperty = DependencyProperty.Register("Children", typeof(UIElementCollection), typeof(MyControl), null);

    public UIElementCollection Children
    {
        get { return (UIElementCollection)GetValue(ChildrenProperty); }
        set { SetValue(ChildrenProperty, value); }
    }

    protected override Size MeasureOverride(Size availableSize)
    {
        Children.Clear();
        UserControl child = new SecondUserControl();
        child.Measure(availableSize);
        Children.Add(child);
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        foreach (UIElement child in Children)
        {
            child.Arrange(new Rect(0,0, child.DesiredSize.Width, child.DesiredSize.Height));
        }
        return finalSize;
    }
}
4

1 回答 1

0

Oy vey. Whatever it is you're trying to do, that isn't the way to do it.

First, your Children colleciton never makes it to the UI. Just declaring properties and measuring stuff doesn't actually add it to the UI. You have to make sure the children are part of the visual tre by adding them to something on the UserControl.Content.

Second, why are you adding and removing children on every Measure pass? That doesn't make sense for any usecase. The Measure & arrange pass isn't a time to remove/add control, it's a time to measure and arrange control.

于 2013-02-14T01:03:33.340 回答