2013-10-30 25 views
1

我写了一个从Progressbar派生的自定义控件,它在valuechange上实现了动画(该值使用双动画填充,直到达到目标)。GetValue和SetValue不被绑定调用

var duration = new Duration(TimeSpan.FromSeconds(2.0)); 
var doubleanimation = new DoubleAnimation(value, duration) 
{ 
    EasingFunction = new BounceEase() 
}; 
BeginAnimation(ValueProperty, doubleanimation); 

一个新的属性“TargetValue”时,因为用于进度的控件模板具有改变之后直接以显示新的价值。为此,ProgressEx包含以下内容:

public static readonly DependencyProperty TargetValueProperty = DependencyProperty.Register("TargetValue", typeof (int), typeof (ProgressEx), new FrameworkPropertyMetadata(0)); 
    public int TargetValue 
    { 
     get { return (int)GetValue(TargetValueProperty); } 
     set 
     { 
      if (value > Maximum) 
      { 
       //Tinting background-color 
       _oldBackground = Background; 
       Background = FindResource("DarkBackgroundHpOver100") as LinearGradientBrush; 
      } 
      else 
      { 
       if (_oldBackground != null) 
        Background = _oldBackground; 
      } 

      SetValue(TargetValueProperty, value); 
      Value = value; 
     } 
    } 

当TargetValue超过最大我将使用在XAML定义的不同的颜色。这工作真的很好 - 但。现在我想在一个列表视图中使用它绑定到一些数据。问题是,setter在这种情况下不会被调用,所以即使通过TargetValue = {Binding ProgressValue}更改了值,也不会执行动画。我知道框架将总是直接调用GetValue和SetValue,并且不应该提供逻辑,但有没有办法解决这个问题?

在此先感谢。

+0

从[MSDN](http://msdn.microsoft.com/en-us/library/ms753358.aspx#清单):除非特殊情况,你的包装器实现应该分别只执行GetValue和SetValue动作。在[XAML加载和依赖属性](http://msdn.microsoft.com/zh-cn/library/bb613563.aspx)主题中讨论了此原因。 – Clemens

回答

1

CLR风格的获取者和设置者的DependencyProperty s并不意味着被框架调用......他们在那里供开发人员在代码中使用。如果你想知道什么时候DependencyProperty值发生了变化,你需要添加一个处理程序:

public static readonly DependencyProperty TargetValueProperty = 
DependencyProperty.Register("TargetValue", typeof (int), typeof (ProgressEx), 
new FrameworkPropertyMetadata(0, OnTargetValueChanged)); 

private static void OnTargetValueChanged(DependencyObject dependencyObject, 
DependencyPropertyChangedEventArgs e) 
{ 
    // Do something with the e.NewValue and/or e.OldValue values here 
} 
+0

谢谢,这有很大的帮助。在添加虚拟程序以处理新值之后,控件现在可以正常工作。再次感谢。 – Edgar

相关问题