绑定时不调用GetValue和SetValue

时间:2013-10-30 14:11:20

标签: c# wpf dependency-properties

我编写了一个从Progressbar派生的自定义控件,它在valuechange上实现了动画(该值以doubleanimation填充,直到达到目标为止)。

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

使用新属性“TargetValue”,因为用于ProgressBar的ControlTemplate必须在更改后立即显示新值。为此,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,并且不应该提供逻辑,但有没有解决方法呢?

提前致谢。

1 个答案:

答案 0 :(得分:1)

框架调用DependencyProperty的CLR样式的getter和setter ......它们可供开发人员在代码中使用。如果您想知道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
}