Question

I bound a DependencyProperty to a ComboBox.

public static readonly DependencyProperty SelectedItemProperty =
       DependencyProperty.Register("SelectedItem",
       typeof(MyViewModel), typeof(MySelectionViewModel),
       new UIPropertyMetadata(null, new  PropertyChangedCallback(OnSelectedXyPropertyChanged)));

All works fine, but when in OnSelectedXyPropertyChanged a MessageBox is shown the combobox in the back displays the old value. I expected the new value to be displayed because I think the user will be confused if he sees the old value and a message corresponding to the new value.

private static void OnSelectedXyPropertyChanged (DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
   ...
   MessageBoxResult result = MessageBox.Show("Ask something", "Caption", MessageBoxButton.YesNo);
   ...
}

How to change to get the expected behaviour?

Was it helpful?

Solution

Yes, the user will have a disrupting experience if the UI is inconsistent...

Opening a message box is a modal incident in the lifetime of a thread and hence the thread is blocked until the message box closes. In your case, the message box is raised during an event pipeline in which the WPF binding engine is a participant, so the UI does not get updated until the message box is closed.

The fastest way to resolve this is to schedule the message box via the Dispatcher. This will allow the event pipeline to complete. Indicative code for this would be...

Application.Current.Dispatcher.BeginInvoke(...)

Doing this places the delegate into a priority queue that will execute when 'the time is right'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top