c# winforms binding the properties of a ListBox SelectedItem

爷,独闯天下 提交于 2019-12-12 18:04:40

问题


So I have a listbox and a class. This class is called 'Mission' and has three properties: Name, IsStarted and IsCompleted.

I have used a BindingList and set the datasource of the Listbox to that BindingList. This works fine, no problems so far.

What I don't know how to do (and I hope it's possible) is to bind the properties IsStarted and IsCompleted to two CheckBoxes, so that if I change which Mission is selected, those CheckBoxes will change to reflect the properties of the SelectedItem.

I appreciate I can do this by using the event of SelectedItemChanged on the ListBox, but I would like to have a two way binding so that if I were to check or uncheck the CheckBoxes, the data in the class would change.


回答1:


You don't need to use events, it's enough to use data binding:

missionsListBox.DataSource = bindingList;
missionsListBox.DisplayMember = "Name";
isStartedCheckBox.DataBindings.Add("Checked", bindingList, "IsStarted");
isCompletedCheckBox.DataBindings.Add("Checked", bindingList, "IsCompleted")

This way, the ListBox will act as an index for mission objects and it shows a list of missions. When you select an item, it shows values of IsStarted and IsCompleted in corresponding check box controls and you can change those values for selected item using check boxes.



来源:https://stackoverflow.com/questions/43699612/c-sharp-winforms-binding-the-properties-of-a-listbox-selecteditem

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