VS2008 Two-way data binding: how to make it work?

I am a bit stuck playing with DataBinding in a tryout project. I have a simple form with just a spinbox that I want to bind to a form member.

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 VS IDE, the Data section of the My Fields window allows me to select Form1.data as my data source, but

  • the spinbox does not initialize 10 as I would expect
  • changing the spinbox value does not call get / set from Data.value.

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

+1


a source to share


1 answer


For objects => update control: your event won't raise - auto-implemented properties don't care about INotifyPropertyChanged

- you'll need to move it:

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 your binding set up correctly. You have to bind to a property Data.Value

and you will need to tell about this instance Data

at runtime:



  someBindingSource.DataSource = data;

      

Or, if you use DataBindings

directly - below it is shown that it works 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);
    }
}

      

+1


a source







All Articles