从代码头痛中绑定属性

问题描述

| 我试图将文本框的内容绑定到我在控件内部创建的属性,但是没有成功。我已经找到了其他方法,但是很麻烦,我希望更简单一些。无论如何,这是最终的代码
public partial class DateListEditor : UserControl,INotifyPropertyChanged {
    private int _newMonth;
    public int newMonth {
      get { return _newMonth; }
      set { 
        if(value < 1 || value > 12)
          throw new Exception(\"Invalid month\");
        _newMonth = value; 
        NotifyPropertyChanged(\"newMonth\");
      }
    }

    public DateListEditor() {
        InitializeComponent();
        DataContext = this;
        newMonth = DateTime.Now.Month;
    }

    // ...
然后在XAML中:
<TextBox x:Name=\"uiMonth\" Text=\"{Binding newMonth,Mode=TwoWay,ValidatesOnExceptions=True}\"/>
这东西行得通。它将用当前月份预填充文本框,并在失去焦点时进行验证:太好了。 但是,如何避免使用XAML行,并通过代码完成所有操作?我似乎无法解决这个问题。我已经试过这段代码,但是什么也没有发生:
  InitializeComponent();
  Binding b = new Binding(\"Text\") {
    Source = newMonth,ValidatesOnExceptions = true,Mode = BindingMode.TwoWay,};
  uiMonth.SetBinding(TextBox.TextProperty,b);

  DataContext = this;
如何在不设置XAML绑定的情况下做到这一点?     

解决方法

尝试更改此行,看看是否有帮助
//oldway    
Binding b = new Binding(\"Text\")

//newway
Binding b = new Binding(\"newMonth\")
您提供给绑定的路径应该是所需属性的路径。您在哪里设置源,您甚至可以将其留空     ,+1 tam,不要忘记来源:
Binding b = new Binding(\"newMonth\"){
  Source = this,// the class instance that owns the property \'newMonth\'
  ValidatesOnExceptions = true,Mode = BindingMode.TwoWay,};