WPF MVVM New Editable Combobox Value Is Null

advertisements

Tried all the solutions for similar issues around here, still no go. I have a ComboBox that should work for selection of existing items and/or for adding new ones. Only the selected item part works. Category is just an object with a Name and Id.

Thanks in advance!

XAML

<ComboBox Name="CbCategory" ItemsSource="{Binding Categories}"
    SelectedItem="{Binding SelectedCategory.Name, UpdateSourceTrigger=PropertyChanged}"
    Text="{Binding NewCategory.Name}" DisplayMemberPath="Name"
    IsEditable="True"/>

Code behind

private Category _selectedCategory;

public Category SelectedCategory
{
    get { return _selectedCategory; }

    set
    {
        if (Equals(_selectedCategory, value)) return;
        _selectedCategory = value;
        SendPropertyChanged("SelectedCategory");
    }
}

private Category _newCategory;

public Category NewCategory
{
    get { return _newCategory; }

    set
    {
         if (Equals(_newCategory, value)) return;
         _newCategory = value;
          SendPropertyChanged("NewCategory");
    }
}


Your Text Binding doesn't work because you're binding against a null Category property. Instantiate it instead.

public Category NewCategory
{
    get { return _newCategory ?? (_newCategory = new Category()); }
    set
        {
          if (Equals(_newCategory, value)) return;
          _newCategory = value;
           SendPropertyChanged("NewCategory");
         }
}

Edit: Elaborating as per your comment:

Your ComboBox.Text binding is set to "{Binding NewCategory.Name}", so no matter what the value of SelectedCategory is, the Text property will always reflect the name of the NewCategory.

When NewCategory is null, the Text property has nothing to bind to, and therefore the 2-way binding cannot be executed (that is, the value of the Text property cannot be passed back to NewCategory.Name, because that will cause an NullReferenceException (because the NewCategory is null).

This does not affect the case of the SelectedItem, because that's binding directly to the SelectedCategory property, and not a sub-property of that.