質問

I am trying to implement my own control, which can host one or more children of the same type as the control itself:

<local:MyControl x:Name="control1">
    <local:MyControl x:Name="control2">
        <local:MyControl x:Name="control3">
            <local:MyControl x:Name="control4">
                <local:MyControl x:Name="control5">
                    <local:MyControl x:Name="control6">
                        <local:MyControl x:Name="control7"/>
                    </local:MyControl>
                </local:MyControl>
            </local:MyControl>
       </local:MyControl>
   </local:MyControl>
</local:MyControl>

The problem that I have is that only the first instance is known as root and the others are children of the first one. And they may even be children of each other.

Here the code for MyControl class:

[ContentProperty("MyChildren")]
class MyControl : ItemsControl
{ 
    public List<MyControl> MyChildren
    {
        get { return (List<MyControl>)GetValue(MyChildrenProperty); }
        set { SetValue(MyChildrenProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Children.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyChildrenProperty =
        DependencyProperty.Register("MyChildren", typeof(List<MyControl>), typeof(MyControl), new UIPropertyMetadata(new List<MyControl>()));
}

This code is what I have tried, but this isn't working.

How do I implement a custom control that can host child controls of the same type, in which it should be possible to do things like in the example above?

役に立ちましたか?

解決

You are asking something without doing any kind of research before. I know what I am talking about because if you had asked google about this, you would have known that controls in wpf need to be in visualtree and/or logicaltree and futhermore you would have read somewhere that controls shall not be stored in a simple list but instead in a UIElementCollection which manages adding and removing controls to or from visualtree automatically for you.

Just google your issue please and you will know what I am talking about. There are tons of tutorials about how to write a custom controls. There are awesome tuts on msdn about custom controls in wpf.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top