C# – ComboBox SelectedIndex MVVM WPF

ccomboboxmvvmwpfxaml

I have a ComboBox bound to an ObservableCollection of tbPublications which populates as it should. I then select a row from a DataGrid which fires another Create form in which I insert a new record into tbPublications, all good.

When I close said create form and return to my ComboBox form I am clearing and re-reading in the one new item to my ObservableCollection, returning the user to the item they've just created. The ComboBox then displays the one item from my newly populated collection, all good.

My problem is that on returning to my ComboBox form, the new publication is not set as selected item in the ComboBox display, the user has to click the ComboBox then select the item.

I can't use SelectedIndex = "0" in my view XAML as I want to show the whole ObservableCollection in my ComboBox on page load.

Is there any way to use a method in the ViewModel maybe to solve this issue, something maybe such as..

      private void SetSelectedIndex()
      {
        if (MyObservableCollection.Count == 1)
        {
            //Set selected indexer to "0";
        }
      }

Found a solution to this, not sure if it's the cleanest 'MVVM' solution…

After reading in my ObservableCollection I invoke this method:

 if (_ModelPublicationsObservableList.Count == 1)
                {
                    SelectedPublication = _ModelPublication;
                    SetSelectedIndex();
                }

Here's the method which gets the current main window and sets the SelectedIndex:

 private void SetSelectedIndex()
    {
        ArticlesDataGridWindow singleOrDefault = (ComboBoxWindow)Application.Current.Windows.OfType<ComboBoxWindow>().SingleOrDefault(x => x.IsLoaded);
        singleOrDefault.comboBox1.SelectedIndex = 0;        
    }

Best Answer

Did you consider using the SelectedItem property of combobox? You can bind the selected item property of combobox to get or set the selected item.

XAML

<ComboBox ItemsSource="{Binding Path=Publications}" SelectedItem="{Binding Path=SelectedPublication, Mode=TwoWay}" />

ViewModel

public class ItemListViewModel
{
    public ObservableCollection<Publication> Publications {get; set;}

    private Publication _selectedPublication;
    public Publication SelectedPublication 
    {
        get { return _selectedPublication; }
        set
        {
            if (_selectedPublication== value) return;
            _selectedPublication= value;
            RaisePropertyChanged("SelectedPublication");
        }
    }
}

If you want to set the selected item from View model,You can set the SelectedPublication property as-

SelectedPublication = Publications[0];

Or you can locate the required item in the Publications collection and assign it to SelectedPublication property.

Related Topic