PropertyChangedEventHandler为null

时间:2013-01-10 19:45:01

标签: c# .net wpf binding inotifypropertychanged

我有以下类,它将是绑定源:

public class Timeline : Canvas, INotifyPropertyChanged
{

  public static readonly DependencyProperty TimeTextBindingPropProperty;
  public event PropertyChangedEventHandler PropertyChanged;

  private void OnPropertyChanged(string name)
  {
    if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(name));
  }

  public double TimeTextBindingProp
  {
    get { return (double)GetValue(TimeTextBindingPropProperty); }
    set 
    {
      SetValue(TimeTextBindingPropProperty, value);
      OnPropertyChanged("TimeTextBindingProp");
    }
  }

  static Timeline()
  {
    TimeTextBindingPropProperty = DependencyProperty.Register("TimeTextBindingProp", typeof(double), typeof(Timeline));
  }
}

然后我在主窗口设置文本框的Text属性和timeline's TimeTextBindingProp属性之间的绑定:

private void InitTextBinding()
{
  timeTextBinding = new Binding();
  timeTextBinding.Mode = BindingMode.OneWay;
  timeTextBinding.Source = timeline;
  timeTextBinding.Path = new PropertyPath("TimeTextBindingProp");
  timeTextBinding.Converter = new TimeTextConverter();

  BindingOperations.SetBinding(this.timeTextBox, TextBox.TextProperty, timeTextBinding);
}
即使设置了绑定并呈现PropertyChangedtimeline的{​​{1}}处理程序仍为null。我做错了什么?

修改

我在xaml中声明timeTextBox和timeline,如下所示:

timeline

2 个答案:

答案 0 :(得分:2)

你的TimeTextBindingProp是一个依赖属性,并且在基类中有一个NotificationChange机制。你自己的OnPropertyChanged是多余的,显然没有使用它。

绑定仍然应该工作。

答案 1 :(得分:2)

除了设置timeTextBox.Text之外,您的代码是否更新timeTextBinding?也许你直接在代码隐藏中将timeTextBox.Text设置为某个值,或者你还有其他一些绑定它?

由于timeTextBinding只是 OneWay ,因此无法将此类更改写回TimeTextBindingProp,只会覆盖并删除绑定(没有任何警告),{{ 1}}将重置为timeline.PropertyChanged

相关问题