0

I have a UserControl MyParentControl which has another control inside (TreeView). I expose this control as a dep property say TreeView MyChildControl.

Then in XAML which uses MyParentConrol I want to access all the TreeView properties, for example Style.

I want to write something like:

<my:MyParentControl>
    <my:MyParentControl.MyChildControl.Style>
        <Style />
    </my:MyParentControl.MyChildControl.Style>
</my:MyParentControl>

Is there a way to achieve that?

4

2 回答 2

2

By exposing the DependencyProperty for your inner control you have solved half of the problem - ie you can set individual properties in xaml.

The next step is to have those property setters affect the child control.

There are two options to achieve that.

  1. In your control template, define your child control and use Bindings on each property you want to set.

  2. Define a container element in your parent control template and set it's content to your child whenever the dependency property changes.

Although both of these methods could work, you may find that the solution involving the least amount of code, and the greatest amount of flexibility, is to expose a Style property for your child control and apply that in the control template.

public class ParentControl : Control
{
    public Style ChildControlStyle
    {
        get { return (Style)GetValue(ChildControlStyleProperty); }
        set { SetValue(ChildControlStyleProperty, value); }
    }

    public static readonly DependencyProperty ChildControlStyleProperty =
        DependencyProperty.Register("ChildControlStyle", 
                                    typeof(Style), 
                                    typeof(ParentControl), 
                                    new PropertyMetadata(null));
}

<Style TargetType="ParentControl">
    <Setter Property="ChildControlStyle">
        <Setter.Value>
            <Style TargetType="ChildControl">
                <!-- setters -->
            </Style>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ParentControl">
                <Grid>
                    <ChildControl Style="{TemplateBinding ChildControlStyle}" />
                    <!-- other stuff -->
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
于 2013-03-31T09:41:38.717 回答
1

You would get that effect by writing XAML like this:

<my:MyParentControl>
   <my:MyParentControl.Resources>
      <Style TargetType="my:MyChildControl">
         <Setter Property="Background" Value="Red"/>
      </Style>
   </my:MyParentControl.Resources>
<my:MyParentControl>

In this example, this XAML creates a MyParentControl in which all the children of type MyChildControl have red backgrounds.

于 2013-03-31T09:11:15.817 回答