0

我制作了一个用户控件并添加了一个新属性,如下所示:

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();
    }
}

我的问题是:在我的自定义控件的 XAML 中,我该如何使用它?

4

1 回答 1

2

您可以绑定到控件的 XAML 中的属性:

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

如果DataContext = this;在 MyControl 的构造函数中设置,可以省略RelativeSource绑定的:

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

请注意,不需要静态构造函数。你可以这样写:

public static readonly DependencyProperty SelectedBrushProperty =
    DependencyProperty.Register("SelectedBrush", typeof(Brush), typeof(MyControl),
                                new PropertyMetadata(Brushes.AliceBlue));
于 2013-02-16T18:04:28.503 回答