【问题标题】:Use Property in UserControl在 UserControl 中使用属性
【发布时间】:2013-02-16 17:19:11
【问题描述】:

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

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

【问题讨论】:

  • <local:MyControl SelectedBrush="White" /> .. 不知道你在这里追求什么.. 你能扩大你的问题吗?

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


【解决方案1】:

您可以绑定到控件的 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));

【讨论】:

  • 完美,正是我想要的!
  • 哇,我对你从那个问题中选择了这一点印象深刻。顺便说一句,AncestorType 不应该是MyControl,所以找不到任何UserControl
  • @Default AncestorType 也可以是 local:MyControl,但这需要另一个 XML 命名空间声明,例如 xmlns:local="clr-namespace:MyNamespace"。对我来说似乎没有必要,因为祖先层次结构中没有其他 UserControl。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
相关资源
最近更新 更多