我做了一个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中,我该如何使用它?
答案 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));