1

I have List<string> MyList with 4 values. These are shown in a ComboBox control. The binding works perfectly in my MVVM WPF project.

I also have a string SelectedMyList which binds to my XAML and is supposed to show the selected item. The problem I have is, regardless of using SelectedItem or SelectedValue, it always passes the first item in MyList

private MyClass()//constructor
{
    MyList = new List<string>() {"Hi", "Bye", "Hello", "See ya"}; 
}

private string _selectedMyList;
public string SelectedMyList
{
    get
    {
        return this._selectedMyList;
    }
    set
    {
        //value is always Hi
        if (this._selectedMyList== value)
            return;

        this._selectedMyList= value;
        OnPropertyChanged("SelectedMyList");
    }
}

private List<string> _myList;
public List<string> MyList
{
    get
    {
        return this._myList;
    }
    set
    {
        if (this._myList== value)
            return;

        this._myList= value;
        OnPropertyChanged("MyList");
    }
}

And my XAML

<ComboBox ItemsSource="{Binding MyList}" SelectedValue="{Binding SelectedMyList, UpdateSourceTrigger=PropertyChanged}" />

There are no errors/binding errors etc in the output window.

Why does the SelectedItem/SelectedValue not pass what I consider to be the selected item from the ComboBox?

daniele3004
  • 13,072
  • 12
  • 67
  • 75
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120

2 Answers2

0

This works for me.

  private string _selectedMyList;
    public string SelectedMyList
    {
        get
        {
            return this._selectedMyList;
        }
        set
        {
            //value is always Hi
            if (this._selectedMyList != value)
            {
                this._selectedMyList= value;
                OnPropertyChanged("SelectedMyList");
            }
        }
    }

    private List<ObservableCollection> _myList;
    public ObservableCollection<string> MyList
    {
        get
        {
            return this._myList;
        }
        set
        {
            if (this._myList== value)
            {
                this._myList= value;
                OnPropertyChanged("MyList");
            }
        }
    }

Xaml:

<ComboBox ItemsSource="{Binding MyList}" 
          SelectedItem="{Binding SelectedMyList}" 
          IsSynchronizedWithCurrentItem="True"/>
d.moncada
  • 16,900
  • 5
  • 53
  • 82
0

If you want to use the SelectedValue attribute then you need to use it with the SelectedValuePath attribute. See this link to a similar question.

Community
  • 1
  • 1
Andrew N
  • 502
  • 7
  • 20