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 the general case (
ValueMember
is not specified) if you bind to a composite object you can leverageSelectedValue
which should equalsSelectedItem
.As mentioned by Andrey
ListBox
provides real-time notification forSelectedValue
value changes.So this code should be enough:
There is one side effect: setting
CurrentItem
will not update theListBox
.In master-detail views this should be OK: at the beginning you just have to ensure that the
SelectedItem
(the first by default) is consistent with theCurrentItem
, then the workflow is driven by the master, theListBox
.If this is an issue then go for Andrey's solution.
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:
Use DataSourceUpdateMode.OnPropertyChanged