Archive for May, 2009

Cancel Selection Change

May 20, 2009

The situation: the user has changed a selection in, say, combobox. Your event handler  Combobox_SelectionChanged() asks the user: “Are you sure?” and the user answers: “No! Cancel!” How can you cancel the selection?

One way is described in: http://amazedsaint.blogspot.com/2008/06/wpf-combo-box-cancelling-selection.html

Really previous selection is e.RemovedItems(0). But if in event handler  Combobox_SelectionChanged()you assign:

Combobox.SelectedItem = e.RemovedItems(0)

then your event handler will be called again! And again.

Amazedsaint proposed to use global variable. Not very clean solution. I propose to remove event handler assignment before the command Combobox.SelectedItem = e.RemovedItems(0) and reassign it afterwards, e.g.:

Sub Combobox_SelectionChanged()

If MessageBox.Show(“Are you sure”,MessageBox.YesNo)<>MessageBox.Yes Then

Dim cbo as ComboBox=CType(sender,ComboBox)

RemoveHandler Combobox.SelectionChanged, AddressOf Combobox_SelectionChanged

cbo.SelectedItem=e.RemovedItems(0)

AddHandler combobox.SelectionChanged, AddressOf combobox_SelectionChanged

End If

End Sub

One another issue with “Cancellation of User Changes” is changes made in binded data. If you don’t want to change data before the user assume it, you can use

UpdateSourceTrigger=Explicit

and change your data directly or via BindingExpression.UpdateSource().

Hope it helps.