2011-04-14 53 views
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

尝试改变这一行,看看它是否有助于

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

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

你给的结合应该是路径到你想要的属性的路径。你在哪里设置源,你甚至可以离开这个空白

+0

十分感谢!我从来没有能够明白项目去哪里:) – Palantir 2011-04-15 09:26:54

2

+1潭,不要忘记来源:

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

非常有帮助,谢谢! – Palantir 2011-04-15 09:27:40