我创建了一个派生自 Canvas
的控件,它应该绘制一个实时图表,给定值通过绑定(bind)传递给 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);
}
}
我这样绑定(bind)控件:
<mystuff:Plotter Value="{Binding MyViewModelProperty}" Height="50" Width="200" />
我的 ViewModel 实现了 INotifyPropertyChanged
并正确调用了 PropertyChanged
。如果我将 MyViewModelProperty
绑定(bind)到文本框,它每次都会正确更新。只有当我将它绑定(bind)到我自己的控件时,我的 ValueChangedCallBack
才在页面加载时被调用一次,然后再也不会调用。
我在这里没有看到什么?感谢您的帮助!
已解决:我不必在回调中显式设置 Value
。
最佳答案
您在属性值更改的回调中设置属性值。这在任何情况下都没有多大意义。但是,本地设置的值是否会覆盖绑定(bind)值,从而导致您的绑定(bind)不再设置在依赖项属性上?
关于c# - 依赖属性 : PropertyChangedCallBack only called once,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10139475/