Binding WinForms ListBox to object properties

旧城冷巷雨未停 提交于 2019-12-22 17:46:18

问题


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?


回答1:


Use DataSourceUpdateMode.OnPropertyChanged

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



回答2:


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();



回答3:


In the general case (ValueMember is not specified) if you bind to a composite object you can leverage SelectedValue which should equals SelectedItem.

As mentioned by Andrey ListBox provides real-time notification for SelectedValue value changes.

So this code should be enough:

listBox.DataBindings.Add("SelectedValue", controller, "CurrentItem", true, DataSourceUpdateMode.OnPropertyChanged);

There is one side effect: setting CurrentItem will not update the ListBox.

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 the CurrentItem, then the workflow is driven by the master, the ListBox.

If this is an issue then go for Andrey's solution.



来源:https://stackoverflow.com/questions/1815828/binding-winforms-listbox-to-object-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!