绑定代码头痛的属性

时间:2011-04-14 13:19:01

标签: data-binding silverlight-4.0

我试图将文本框的内容绑定到我在控件中创建的属性,但没有成功。我找到了另外一种方法,但它很复杂,我更喜欢更简单的东西。无论如何,这是最终的代码:

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中设置绑定,我该怎么办?

2 个答案:

答案 0 :(得分:2)

尝试更改此行并查看是否有帮助

//oldway    
Binding b = new Binding("Text")

//newway
Binding b = new Binding("newMonth")

您给Binding的路径应该是您想要的属性的路径。你在哪里设置源,你甚至可以留下那个空白

答案 1 :(得分:2)

+1 tam,不要忘记来源:

Binding b = new Binding("newMonth"){
  Source = this, // the class instance that owns the property 'newMonth'
  ValidatesOnExceptions = true,
  Mode = BindingMode.TwoWay,
};