Prathap
Prathap

Reputation: 49

How to change the background color of child control xaml

I have a usercontrol which contains an ellipse inside the Canvas. I am using this control in another window and when i set the background color, i want to change only the background of ellipse.How to change the ellipse(child) background without changing canvas(parent) background color?

Upvotes: 2

Views: 2571

Answers (1)

James Durda
James Durda

Reputation: 645

1. Add a DependencyProperty to the code-behind of your MyUserControl.

Note the 3rd parameter of the Register method is whatever the Type name is of your UserControl

    public Brush EllipseFill
    {
        get { return (Brush)GetValue(EllipseFillProperty); }
        set { SetValue(EllipseFillProperty, value); }
    }

    public static readonly DependencyProperty EllipseFillProperty =
        DependencyProperty.Register("EllipseFill", typeof(Brush), typeof(MyUserControl), new PropertyMetadata(null));

2. Add a reference to the xaml file of both the main Window and the UserControl for the namespace where MyUserControl is defined :

xmlns:local="clr-namespace:WpfApplication1"

3. Bind the Fill property of your Ellipse to the dependency property that was defined on MyUserControl.

Note the use of MyUserControl in AncestorType parameter of the RelativeSource binding.

<Viewbox>
    <Canvas Width="100" Height="100">
        <Ellipse Width="50"
                    Height="20"
                    Canvas.Top="50"
                    Canvas.Left="50"
                    Fill="{Binding Path=EllipseFill, 
                           RelativeSource= {RelativeSource Mode=FindAncestor, 
                                                           AncestorType={x:Type local:MyUserControl}}}"
                    />
        <Rectangle Width="20"
                    Height="40"
                    Canvas.Top="10"
                    Canvas.Left="10"
                    Fill="Blue"
                    />
    </Canvas>
</Viewbox>

4. Set the EllipseFill property on MyUserControl in the main Window

<local:MyUserControl EllipseFill="Red"/>

Upvotes: 3

Related Questions