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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With