0
votes

SO I have a WPF MVVM application. When I press a button, I want a new entry to be added to the dropdown in a combobox, and for the combobox's selected item to be set to that item. I'm able to get the item added to the dropdown through an ObservableCollection, but I can't seem to bind the SelectedItem properly. I have tried:

<ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />

And putting the SelectedItem directly in the ViewModel implementing INotifyPropertyChanged in the ViewModel. But this does not work. Any ideas?

EDIT: I should also add that the OnNotifyPropertyChange event does fire correctly when I expect it to, so I'm not sure what's going on. I also tried using UpdateSourceTrigger=PropertyChanged to no avail.

3

3 Answers

1
votes

Just a small advice to avoid such a situation where you write the name of the property incorect.

If you're using .net 4.5 you can use the CallerMemberName-Attribute in your OnPropertyChanged-Method. This looks like:

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)

Then you're property looks something like

public bool MyProperty
{
   get{ return myProperty; }
   set
   {
      myProperty=value;
      OnPropertyChanged();
   }
}

You also can write a method which extracts you the propertyname out of a lambda-expression. The method in a base-class looks like:

public static class Helper
{
   public static string GetPropertyName<T>(Expression<Func<T>> expression)
   {
      return ((MemberExpression)expression.Body).Member.Name;
   }
}

The usage in a property than looks like:

public bool MyProperty
{
   get{ return myProperty; }
   set
   {
      myProperty = value;
      OnPropertyChanged(Helper.GetPropertyName(() => MyProperty));
   }
}

With this approach you have a compile-time-check of your property-name.

1
votes

Thanks guys, I spelled the property wrong in the OnNotifyPropertyChanged...Good grief.

1
votes

You can also use

OnPropertyChanged(nameof(MyProperty));

to avoid missspellings.

I started to use Fody with PropertyChanged which injects the OnPropertyChanged Code automatically saving you some typing work and makes the code look nice and clean.