在UserControl中使用Property

时间:2013-02-16 17:19:11

标签: c# wpf xaml custom-controls property-binding

我做了一个usercontrol并添加了一个像这样的新属性:

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中,我该如何使用它?

1 个答案:

答案 0 :(得分:2)

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

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

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

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

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

public static readonly DependencyProperty SelectedBrushProperty =
    DependencyProperty.Register("SelectedBrush", typeof(Brush), typeof(MyControl),
                                new PropertyMetadata(Brushes.AliceBlue));