开发者

Bind a property from code headache

开发者 https://www.devze.com 2023-02-24 11:32 出处:网络
I have tried to bind the contents of a textbox to a property I created inside the control, but without success. I have found a way to do it otherwise, but it 开发者_高级运维is convoluted, and I\'d pre

I have tried to bind the contents of a textbox to a property I created inside the control, but without success. I have found a way to do it otherwise, but it 开发者_高级运维is convoluted, and I'd prefer something simpler. Anyway, this is the final code:

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;
    }

    // ...

Then in the XAML:

<TextBox x:Name="uiMonth" Text="{Binding newMonth, Mode=TwoWay, ValidatesOnExceptions=True}"/>

This thing works. It will pre-fill the textbox with the current month, and validate it when focus is lost: great.

But how can I avoid the XAML line, and do everything from code? I can't seem to be able to work this out. I have tried this code, but nothing happens:

  InitializeComponent();
  Binding b = new Binding("Text") {
    Source = newMonth,
    ValidatesOnExceptions = true,
    Mode = BindingMode.TwoWay,
  };
  uiMonth.SetBinding(TextBox.TextProperty, b);

  DataContext = this;

How can I do it without setting the binding in the XAML?


Try changing this line and see if it helps

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

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

the path you are giving to the Binding should be the Path to the property you want. where you are setting the source you might even be able to leave that blank


+1 tam, and don't forget about the source:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号