SelectedItem in ObservableCollection

12,800

Create a class containing both your list of items and the selected item:

public class ViewModel
{
    public string[] Items { get; set; }
    public string SelectedItem { get; set; }
}

Initialize it in code behind and set it as DataContext:

DataContext = new ViewModel
{
    Items = new string[] { "0", "1", "2", "3", "4", "5" },
    SelectedItem = "5"
}

Now bind both properties to your ComboBox:

<ComboBox x:Name="_criteria" 
          ItemTemplate="{StaticResource _ComboBoxTemplate}"
          ItemsSource="{Binding Items}"
          SelectedItem="{Binding SelectedItem}"/>

If you set two way binding for SelectedItem the value in DataContext will even update automatically when the user changes it.

Why did you mention ObservableCollection in the title?

Share:
12,800
BBH1023
Author by

BBH1023

Updated on June 04, 2022

Comments

  • BBH1023
    BBH1023 almost 2 years

    I have:

    <DataTemplate x:Name="_ComboBoxTemplate" x:Key="_ComboBoxTemplate">
        <StackPanel Orientation="Horizontal">
            <StackPanel>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                    <TextBlock VerticalAlignment="Center" Text="{Binding}" FontSize="24"/>
                </StackPanel>
            </StackPanel>
        </StackPanel>
    </DataTemplate>
    
    <ComboBox x:Name="_criteria" ItemTemplate="{StaticResource _ComboBoxTemplate}" ItemsSource="{Binding}"/>
    

    In the code behind:

    this.DataContext = new string[] { "0", "1", "2", "3", "4", "5" };
    

    How do I get it so that the default SelectedItem in ComboBox is 5?