问题
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