0

I've made a usercontrol and added a new property like this:

public partial class MyControl : UserControl
{
    public static readonly DependencyProperty SelectedBrushProperty;
    static MyControl() {
        SelectedBrushProperty = DependencyProperty.Register("SelectedBrush",
                                                            typeof(Brush),
                                                            typeof(MyControl),
                                                            new PropertyMetadata(Brushes.AliceBlue));
    }

    public Brush SelectedBrush {
        get {
            return (Brush)GetValue(SelectedBrushProperty);
        }
        set {
            SetValue(SelectedBrushProperty,value);
        }
    }
    public MyControl()
    {
        InitializeComponent();
    }
}

My question is: When in the XAML of my custom control, how can I use it?

Clemens
  • 123,504
  • 12
  • 155
  • 268
Groulien
  • 59
  • 6

1 Answers1

2

You may bind to the property in the XAML of your Control:

<UserControl x:Class="MyNamespace.MyControl" ...>
    <Grid>
        <Label Background="{Binding SelectedBrush,
            RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
    </Grid>
</UserControl>

If you set DataContext = this; in the constructor of MyControl, you may omit the RelativeSource of the binding:

<Label Background="{Binding SelectedBrush}"/>

Note that there is no need for the static constructor. You could write this:

public static readonly DependencyProperty SelectedBrushProperty =
    DependencyProperty.Register("SelectedBrush", typeof(Brush), typeof(MyControl),
                                new PropertyMetadata(Brushes.AliceBlue));
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Perfect, exactly what I was looking for! – Groulien Feb 16 '13 at 18:53
  • Wow, I'm impressed that you picked that up from that question.. BTW, shouldn't the `AncestorType` be of `MyControl`, so that not any `UserControl` is found? – default Feb 18 '13 at 11:34
  • @Default The AncestorType could as well be `local:MyControl`, but that would require another XML namespace declaration like `xmlns:local="clr-namespace:MyNamespace"`. Seems unnecessary to me, as there is no other UserControl in the ancestor hierarchy. – Clemens Feb 18 '13 at 11:49