views:

205

answers:

1

I'm a bit stuck playing with DataBinding in a tryout project. I have a simple form with just a spinbox, which I want to bind to a member of the form.

class Form1 {
    public class Data : System.ComponentModel.INotifyPropertyChanged {
        int _value = 10;
        public int value {get;set;}
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    }

    public Data data; // the member I want to bind to

}

In the VS IDE, the Data section in the Properties of my spin box allows me to select Form1.data as a data source, but

  1. the spinbox isn't initialized with 10, as I would expect
  2. changing the spinbox value doesn't trigger the get/set of Data.value.

And I just can't live with that. Any ideas?

+1  A: 

For object=>control updates: your event will not be raised - automatically implemented properties don't care about INotifyPropertyChanged - you'll need to move it out:

public class Data : INotifyPropertyChanged {
    int _value = 10;
    public int Value {
        get {return _value;}
        set {
            if(value != _value) {
                _value = value;
                OnPropertyChanged("Value");
            }
        }
    }
    protected virtual void OnPropertyChanged(string propertyName) {
         var handler = PropertyChanged;
         if(handler != null) {
              handler(this, new PropertyChangedEventArgs(propertyName));
         }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

But for the other (control=>object), I expect you don't have the binding setup correctly. You should be binding to the Data.Value property, and you'll need to tell it about your Data instance at runtime:

  someBindingSource.DataSource = data;

Or if you are using DataBindings directly - the following shows it working with the above type:

static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();

        Data data = new Data();
        data.PropertyChanged += delegate {
            Debug.WriteLine("Value changed: " + data.Value);
        };
        Button btn;
        NumericUpDown nud;
        Form form = new Form {
            Controls = {
                (nud = new NumericUpDown()),
                (btn = new Button {
                    Text = "Obj->Control",
                    Dock = DockStyle.Bottom })
            }
        };
        nud.DataBindings.Add("Value", data, "Value",
                       false, DataSourceUpdateMode.OnPropertyChanged);
        btn.Click += delegate { data.Value++; };
        Application.Run(form);
    }
}
Marc Gravell