views:

338

answers:

3

I am doing some WinForms coding for the first time and am trying to use data bindings.

I have a listbox which I bind to an array of strings from my controller object and I also want to bind the SelectedItem from the list box to another string property on the controller so I can track it.

listBox.DataSource = controller.ItemNames;
listBox.DataBindings.Add(new Binding("SelectedItem", controller, "CurrentItem"));

I want the CurrentItem property on the controller to be updated as soon as the user selects different items in the listbox, but it seems that it will only get updated when focus moves to another item on the form.

Is this the expected behavior? Is there a way to have the SelectedItem binding update immediately?

+3  A: 

Use DataSourceUpdateMode.OnPropertyChanged

listBox.DataBindings.Add(new Binding("SelectedItem", controller, "CurrentItem", 
                                true, DataSourceUpdateMode.OnPropertyChanged));
Jacob Seleznev
A: 

I have the same problem as the initial poster: the update of the bound property happens only when the control has lost the focus.

Setting to the update mode to either OnPropertyChanged or OnValidation does not change the observable behavior in my environment (WinForms, .Net 2.0).

For test reasons I changed the DropDownStyle, but I couldn't see any quicker update of the bound property neither.

mcavigelli
+2  A: 

In general if you need to make your model be updated immediately you need to use Use DataSourceUpdateMode.OnPropertyChanged as suggested in the other post.

But it does not work for ListBox.SelectedItem. The reason is because ListBox does not expose SelectedItemChanged event (but expose SelectedValueChanged and SelectedIndexChanged), so DataBinding have no idea that something has changed in the control.

As a workaround you can put the following lines in the setup code for your control:

listBox.SelectedIndexChanged +=
  (s, args) => listBox.DataBindings["SelectedItem"].WriteValue();