1
votes

I have a combobox of type List. I have the ItemsSource and the ItemSelected bound through the datacontext. If the selected item has been changed then I show a pop up message confirming the users action. On clicking of 'Ok' the selection gets changed. But on clicking of cancel, the selection should be cancelled and previous item should be retained. Below is the property that is bound to SelectedItem of the combobox.

Public SomeClass Sel
{
  get
  {
    return _sel;
  }
  set
  {
    if (_sel != value)
    {
      var sview = _sel;

      if (Compare())
      {
        _sel = value;

        if (Sel != null)
          IsDefault = Sel.IsDefault;
        OnPropertyChanged(() => Sel);
      }
      else
      {
        MessageBoxResult result = MessageBox.Show("Message.", "Owb Message", MessageBoxButton.OKCancel);
        if (result == MessageBoxResult.OK)
        {
          _sel = value;
          if (Sel != null)
            IsDefault = Sel.IsDefault;
          OnPropertyChanged(() => Sel);
        }
        else
        {
          Application.Current.Dispatcher.BeginInvoke(new Action(() =>
          {
            _sel = sview;
            OnPropertyChanged("Sel");
          }), DispatcherPriority.Send, null);
          return;
        }
      }
    }
  }
}

The combo box is in a pop window. So would Dispatcher object work in that case?

3
So, what exactly isn't working?ChrisF♦
retaining the selection on cancel click isn't working. It changes the selection even after cancel click.Virus
_sel = null , OnPropertyChanged("Sel"); or the same with selectedindex = -1ZSH
any more ideas on why this is not working?Virus

3 Answers

1
votes

I'm guessing the selected value is retained, but the View doesn't update correctly.

Have a look at this article: http://www.codeproject.com/Articles/407550/The-Perils-of-Canceling-WPF-ComboBox-Selection. Basically, the few workarounds that did exist in .Net 3.5 no longer work in .Net 4.0..

0
votes

As a general rule, if you've got visual controls leaking into your viewmodel, you're going down a path you don't want to go down.

Create a Behavior that intercepts the OnChanged event of the ComboBox and launches a message box. Here's a tutorial on using behaviours

This keeps all the UI logic in the UI and leaves your viewmodel to manage data and validation.

0
votes

It works like magic now! I missed out setting the value before calling dispatcher. _sel = sview