Search code examples
c#wpfcomboboxitemssourceselectedindex

WPF - Can't set combobox selectedIndex when itemssource changes


I have a combobox that shows a list of items. The list of items displayed is determined by a set of radio buttons. I attach to the radio button clicked events and attempt to set a new itemssource on the combobox. I would like the selectedItem to default to 0, and not -1.

What am I doing wrong?

<Grid>
    <ComboBox Name="cb_Test" />
    <RadioButton Content="List 1" Name="radioButton1" Click="radioButton1_Click" />
    <RadioButton Content="List 2" Name="radioButton2" Click="radioButton2_Click" />
</Grid>
public partial class MainWindow : Window
{
    List<string> list1 = new List<string>() { "list 1", "list 1", "list 1" };
    List<string> list2 = new List<string>() { "list 2", "list 2", "list 2" };
    ComboBoxViewModel viewModel = new ComboBoxViewModel();

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = viewModel;
        cb_Test.ItemsSource = list1;
    }

    private void radioButton1_Click(object sender, RoutedEventArgs e)
    {
        cb_Test.ItemsSource = list1;
        viewModel.SelectedIndex = 0;
    }

    private void radioButton2_Click(object sender, RoutedEventArgs e)
    {
        cb_Test.ItemsSource = list2;
        viewModel.SelectedIndex = 0;
    }
}

public class ComboBoxViewModel : INotifyPropertyChanged
{
    private int selectedIndex;
    public event PropertyChangedEventHandler PropertyChanged;

    public int SelectedIndex
    {
        get { return selectedIndex; }
        set
        {
            if (selectedIndex != value)
            {
                selectedIndex = value;
                NotifyPropertyChanged("SelectedIndex");
            }
        }
    }

    private void NotifyPropertyChanged(string controlName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(controlName));
        }
    }
}

Solution

  • You don't have any databinding to ComboBoxViewModel view model in your XAML, at least provided one. I think that is the problem.