我创建了一个控件,它是从Canvas
派生而来的,应该能够绘制实时图表,通过绑定到一个DependencyProperty传递给它的值。简化版本如下:
public class Plotter : Canvas
{
public float Value { get { return (float)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } }
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(float), typeof(Plotter),
new PropertyMetadata(0f, new PropertyChangedCallback(ValueChangedCallBack)));
public static void ValueChangedCallBack(DependencyObject property, DependencyPropertyChangedEventArgs args)
{
Plotter plotter = (Plotter)property;
plotter.Value = (float)args.NewValue; //<-- Removed this line to get it to work
// Actually draw the value into the canvas geometry
plotter.PlotValue(plotter.Value);
}
}
我是这样绑定控件的:
<mystuff:Plotter Value="{Binding MyViewModelProperty}" Height="50" Width="200" />
我的ViewModel实现了INotifyPropertyChanged接口,并正确地调用了PropertyChanged方法。如果我将MyViewModelProperty绑定到文本框,每次更新时都会正确地更新。但是如果将其绑定到我的自定义控件,我的ValueChangedCallBack只在页面加载时被调用一次,之后就再也没有被调用过了。
我看漏了什么?谢谢您的帮助!
解决:我不必在回调中显式设置Value。