在UserControl中使用属性
本文关键字:属性 UserControl | 更新日期: 2023-09-27 17:59:54
我制作了一个用户控件,并添加了一个新属性,如下所示:
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中时,如何使用它?
您可以绑定到控件的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));