djfoxmccloud
djfoxmccloud

Reputation: 599

Differenciating selection change depending on call from code or changed by hand

I would like to know if it is possible to make a difference in the event selection change of a combobox. I want to make a difference between a user that manually click the combobox and changes its value and a change in the selection that i do from code.

ie :

if i click my combobox and change its value by hand, the event is fired but if i do myCombobox.selectedItem=1 [edit] the events is not fired

Is there an event that has this behaviour in a wpfcombobox ? If not, do you have any idea on how to do that ?

Thanks

[edit] or if it is the binding of the combobox that changes its value

Upvotes: 3

Views: 1206

Answers (2)

competent_tech
competent_tech

Reputation: 44931

You are dealing with a couple of different scenarios, both of which are solvable.

1) Don't process SelectedItem requests during databinding. You have at least two options here:

a) Don't add the event handlers to the control until after databinding is complete or the form is loaded (depending on whether or not databinding is automatic or manual).

b) Set a form level property indicating when it is ok to process the SelectedItem event. You will probably want to set this to true after the form is loaded or after the databinding is complete. In your SelectedItem code, don't perform any actions unless this property is true.

2) Process the SelectedItem logic if the SelectedItem is changed programatically. Again, two options:

a) Extract your logic from the SelectedItem event into a method and then call this method when you perform the logic to set the selected item.

b) Create a custom combobox that inherits from the base and add a SetSelectedItem method (for example) to this inherited combo. This method would then raise the SelectedItem method. This would be reusable and you wouldn't have to remember to do 2 pieces of work whenever you set the SelectedItem manually.

Upvotes: 3

George Duckett
George Duckett

Reputation: 32428

Before you change the selecteditem in code, remove the event handler with -=, then add it back afterwards.

Upvotes: 2

Related Questions