Search code examples
c#wpfxamlcustom-controlsproperty-binding

Use Property in UserControl


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?


Solution

  • 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));