2013-02-11 70 views
0

我想创建一个自定义的图像控件,因为我必须根据某些事件来操作它的源代码,我也会有相当大数量的这种控件。为此,我决定将我的类(“nfImage”)从Image继承,并且我希望有一个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)设置它,则不会发生任何事情,绑定也不起作用。我如何实现这一目标?

回答

1

你不能使用setter,因为XAML不直接调用它:它只是调用SetValue(DependencyProperty,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); } 
    } 
} 
+0

briliant!非常感谢!! – Taras 2013-02-11 22:26:14

1

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

+0

谢谢你的解释。 – Taras 2013-02-11 22:27:20

相关问题