枚举依赖项 属性 从不从视图更新

Enum dependency property never updates from the view

我对作为枚举的用户控件有依赖性 属性。我绑定到它并在主 window 视图中设置它,但它没有改变。

这是用户控件,图标是枚举

<local:GoogleMaterialIcon Icon="AccountBalance"/>

这是枚举

public enum Icon
{
    _3DRotation,
    Accessibility
};

这里是dp

    /// <summary>
    /// Dependency Property used to back the <see cref="Icon"/> Property
    /// </summary>
    public static readonly DependencyProperty IconProperty =
        DependencyProperty.Register("Icon",
            typeof(Icon),
            typeof(GoogleMaterialIcon),
            new PropertyMetadata(null));

最后 属性

public Icon Icon
{
    get { return (Icon)GetValue(IconProperty); }
    set
    {
        SetValue(IconProperty, value);
    }
}

我在设置的图标内放置了一个断点,但它从来没有 运行s。枚举也在它自己的文件中。每次我 运行 它都显示错误的图标,因为 dp 恢复到第一个枚举并且从不更新

更新:后面的用户控件完整代码

public partial class GoogleMaterialIcon : UserControl
{
    /// <summary>
    /// Dependency Property used to back the <see cref="Icon"/> Property
    /// </summary>
    public static readonly DependencyProperty IconProperty =
        DependencyProperty.Register("Icon",
            typeof(Icon),
            typeof(GoogleMaterialIcon),
            new PropertyMetadata(null));


    /// <summary>
    /// Constructor
    /// </summary>
    public GoogleMaterialIcon()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Select a predefined icon to use 
    /// </summary>
    public Icon Icon
    {
        get { return (Icon)GetValue(IconProperty); }
        set
        {
            SetValue(IconProperty, value);
        }
    }
}

显然在某些情况下 - 至少对我来说 - 奇怪的情况下,甚至 Microsoft 也只能提出解决方案而不是解释。

在您的 PropertyMetadata 中,您缺少 PropertyChanged-Event

不幸的是,我无法深入解释这里发生了什么。但是使用 DependencyProperty 的 PropertyChanged-Event 对我来说似乎是一个可以接受的解决方法。