Search code examples
c#wpfcomboboxbinding

ComboBox binding to referenced (relative) source


When binding ComboBox to referenced source:

<ComboBox SelectedValue="{Binding Source.SelectedItem}"
          ItemsSource="{Binding Source.Items}"
          DisplayMemberPath="Name" />

where Source is

SourceType _source;
public SourceType Source
{
    get { return _source; }
    set { _source = value; OnPropertyChanged(); }
}

and SourceType is

public class SourceType: INotifyPropertyChanged
{
    Item _selectedItem;
    public Item SelectedItem
    {
        get { return _selectedItem; }
        set { _selectedItem = value; OnPropertyChanged(); }
    }

    public IReadOnlyList<Item> Items { get; }

    public SourceType(...)
    {
        Items = new List<Items>(...) // **new** list generated from passed arguments
        SelectedItem = Items.First();
    }
}

and Item is

public class Item: INotifyPropertyChanged
{
    string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; OnPropertyChanged(); }
    }
}

following happens:

  • for only one source (if Source never changes) it works: ComboBox display list of Items and correct item is selected (I can see its Name when switching view);
  • for more than one items ComboBox bugs: has no selection (but drop-down list is there and working fine), selection doesn't persist when switching view or Source is changed (e.g. between 2 sources).

It seems like ComboBox has some problems to identify SelectedValue or find it in the ItemsSource. And I can't figure out what is wrong.

Debugging does not uncover anything: Items is set correctly, SelectedItem is first item from Items collection, yet ComboBox is displayed without selection. Why?


Solution

  • I will use a ObservableCollection instead of a List for Items and use SelectedItem for the ComboBox, not SelectedValue.

    Read this great answer for differences between SelectedItem and SelectedValue Difference between SelectedItem, SelectedValue and SelectedValuePath