Wpf 是否将依赖项属性添加到从控件继承的类?

Wpf 是否将依赖项属性添加到从控件继承的类?,wpf,dependency-properties,Wpf,Dependency Properties,我正在尝试创建一个自定义图像控件,因为我必须根据一些事件操作它的源代码,而且我将拥有一个相当大的控件数组。为此,我决定从Image继承我的类(“nfImage”),并且我希望有一个DP(它实际上会反映事件),我可以将它绑定到视图模型。我正在做: class nfImage : Image { public static readonly DependencyProperty TagValueProperty = DependencyProperty.Register("T

我正在尝试创建一个自定义图像控件,因为我必须根据一些事件操作它的源代码,而且我将拥有一个相当大的控件数组。为此,我决定从Image继承我的类(“nfImage”),并且我希望有一个DP(它实际上会反映事件),我可以将它绑定到视图模型。我正在做:

class nfImage : Image
{
    public static readonly DependencyProperty TagValueProperty =
        DependencyProperty.Register("TagValue", typeof(int), typeof(nfImage), new UIPropertyMetadata(0));

    public int TagValue
    {
        get { return (int)GetValue(TagValueProperty); }
        set
        {
            SetValue(TagValueProperty, value);
            if (this.Source != null)
            {
                string uri = (this.Source.ToString()).Substring(0, (this.Source.ToString()).Length - 5) + value.ToString() + ".gif";
                ImageBehavior.SetAnimatedSource(this, new BitmapImage(new Uri(uri, UriKind.Absolute)));
            }
        }
    }
}

问题是它不起作用。如果我从代码隐藏中设置TagValue的值,源代码会更改,但是如果我从xaml(通过dp)设置它,则不会发生任何事情,绑定也不会工作。如何实现这一点?

您不能使用setter,因为XAML不直接调用它:它只调用SetValue(dependencProperty,value),而不经过setter。您需要处理PropertyChanged事件:

class nfImage : Image
{

    public static readonly DependencyProperty TagValueProperty =
        DependencyProperty.Register("TagValue", typeof(int), typeof(nfImage), new UIPropertyMetadata(0, PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        var _this = dependencyObject as nfImage;
        var newValue = dependencyPropertyChangedEventArgs.NewValue;
        if (_this.Source != null)
        {
            string uri = (_this.Source.ToString()).Substring(0, (_this.Source.ToString()).Length - 5) + newValue.ToString() + ".gif";
            //ImageBehavior.SetAnimatedSource(this, new BitmapImage(new Uri(uri, UriKind.Absolute)));
        }
    }

    public int TagValue
    {
        get { return (int)GetValue(TagValueProperty); }
        set { SetValue(TagValueProperty, value); }
    }
}

DependencyProperty的包装器属性只是一个样板,除了GetValue和SetValue之外,它不应该做任何事情。其原因是,在从代码直接调用属性包装器之外设置值的任何操作都不会使用包装器并直接调用GetValue和SetValue。这包括XAML和绑定。您可以向DP声明中的元数据添加PropertyChanged回调,而不是包装器设置器,并在那里执行额外的工作。这是为任何SetValue调用调用调用的