自定义的 WPF 动态值 属性

WPF Dynamic value on a custom property

我有一个用户控件,其中包含扩展器和一些其他控件。

用户控件有一个自定义 "XBackground" 属性,它实际上只为扩展器设置背景。

    public Brush XBackground
    {
        get
        {
            return expander.Background;
        }
        set
        {
            expander.Background = value;
        }
    }

当我使用我的用户控件时,背景只能静态设置,不能动态设置。调试器表示只能通过动态资源设置 DependencyProperty。在这里我被困住了。我试图在我的 XBackground 属性 上注册依赖项 属性 但我收到一条错误消息 "A 'DynamicResourceExtension' can only be set on a DependencyProperty of a DependencyObject."

这是我注册依赖的尝试属性:

public static readonly DependencyProperty BcgProperty = DependencyProperty.Register("XBackground", typeof(Brush), typeof(Expander));

小错误:

public static readonly DependencyProperty BcgProperty = DependencyProperty.Register("XBackground", typeof(Brush), typeof(YourCustomUserControl));

完整版:

public static readonly DependencyProperty XBackgroundProperty 
            = DependencyProperty.Register("XBackground", typeof(Brush), typeof(YourCustomUserControl));
public Brush XBackground
{
    get { return (Brush) GetValue( XBackgroundProperty ); }
    set { SetValue( XBackgroundProperty, value ); }
}
Register 中的

Owner class 不是 Expander,而是注册 DependencyProperty 的 class 的名称。 试试这个:

    public Brush XBackground
    {
        get { return (Brush)GetValue(XBackgroundProperty); }
        set { SetValue(XBackgroundProperty, value); }
    }

    // Using a DependencyProperty as the backing store for XBackground.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty XBackgroundProperty =
        DependencyProperty.Register("XBackground", typeof(Brush), typeof(/typeof your UserControl goes here/), new PropertyMetadata(null));

您不得使用 typeof(Expander),而是将您的 UserControl 的类型用作 Register 方法的 ownerType 参数。此外,您还必须在 属性 包装器中调用 GetValueSetValue

除此之外,您还必须使用 属性 元数据注册一个 PropertyChangedCallback,以获得有关 属性 值更改的通知:

public partial class YourUserControl : UserControl
{
    ...

    public Brush XBackground
    {
        get { return (Brush)GetValue(XBackgroundProperty); }
        set { SetValue(XBackgroundProperty, value); }
    }

    public static readonly DependencyProperty XBackgroundProperty =
        DependencyProperty.Register(
            "XBackground",
            typeof(Brush),
            typeof(YourUserControl),
            new PropertyMetadata(null, XBackgroundPropertyChanged));

    private static void XBackgroundPropertyChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var userControl = (YourUserControl)obj;
        userControl.expander.Background = (Brush)e.NewValue;
    }
}

PropertyChangedCallback 的替代方法是将 Expander 的 Background 属性 绑定到 XAML 中 UserControl 的 XBackground 属性:

<UserControl ...>
    ...
    <Expander Background="{Binding XBackground,
        RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
    ...
</UserControl>