开发者

Binding WinForms ListBox to object properties

开发者 https://www.devze.com 2022-12-12 15:37 出处:网络
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 str开发者_如何学Cings from my controller object and I also want to

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 str开发者_如何学Cings 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();


Use DataSourceUpdateMode.OnPropertyChanged

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消