gliderkite
gliderkite

Reputation: 8928

Change UserControl property using XAML

I have my UserControl

<UserControl x:Class="CustomCtrl.MyButton">
   <Button x:Name="Btn" />
</UserControl>

And I use my UserControl in a Window

<Window>
    <Grid>
        <MyButton Background="Aqua" />
    </Grid>
</Window>

I want to change the Background property of the Button Btn using the property Background of my UserControl with XAML.

I tried adding the Background property

public class MyButton: UserControl
{
    public new Brush Background
    {
        get
        { return Btn.GetValue(BackgroundProperty) as Brush; }

        set
        { Btn.SetValue(BackgroundProperty, value); }
    }        
}

But it has no effect.
Instead if I use the code MyButtonControl.Background = Brushes.Aqua;, it works.
Why? How can I fix this problem?

Upvotes: 1

Views: 2496

Answers (3)

brunnerh
brunnerh

Reputation: 184296

The UserControl.Background is taken, UserControls are not custom controls and you have no control over how this propery is used. If you want to change the background of just one control you can expose a new dependency property and bind it to the Button.Background.

Upvotes: 1

TomBot
TomBot

Reputation: 1146

With

<Window>
    <Grid>
        <MyButton Background="Aqua" />
    </Grid>
</Window>

you are setting the background color of the UserControl. To set the background color of the Button you have to

<UserControl x:Class="CustomCtrl.MyButton">
   <Button x:Name="Btn" Background="Aqua" />
</UserControl>

Edit (after OP comment): You cannot modify the UserControl.Background, but a new property works:

public Brush ButtonBackground {
    get {
        return this.Btn.Background;
    }
    set {
        this.Btn.Background = value;
    }
}

and then:

<Window>
    <Grid>
        <MyButton ButtonBackground="Aqua" />
    </Grid>
</Window>

Upvotes: 0

Eyal H
Eyal H

Reputation: 989

As I see it you have two choices:

  1. The easy way, simply set the "Btn" Background to Transparent like so:

    <UserControl x:Class="CustomCtrl.MyButton">
          <Button x:Name="Btn" Background="Transparent"/>
    </UserControl>
    
  2. another way is to bind the background color of the button to the background color of the control:

    <UserControl x:Class="CustomCtrl.MyButton" x:Name="control">
          <Button x:Name="Btn" Background="{Binding Background, ElementName=control}"/>
    </UserControl>
    

Tested both and seem to work.

Upvotes: 0

Related Questions