How to set default text to combo box using MVVM

I am linking combobox in WPF using the MVVM pattern. I can associate a list of strings with combobox, but I don't know how to set the default value in combobox. Well, I have a list of names that have "A", "B", "C" and "D". Now I want the default "A" to appear as the default.

thank

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ViewModel="clr-namespace:WpfApplication1.ViewModel"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <ViewModel:NameViewModel></ViewModel:NameViewModel>
</Window.DataContext>
<Grid>
    <ComboBox Height="23" Width="120" ItemsSource="{Binding Names}"/>
</Grid>

public class NameViewModel
{
   private IList<string> _nameList = new List<string>();
   public IList<string> Names { get; set; }
   public NameViewModel()
   {
       Names = GetAllNames();
   }

   private IList<string> GetAllNames()
   {
       IList<string> names = new List<string>();
       names.Add("A");
       names.Add("B");
       names.Add("C");
       names.Add("D");
       return names;
   }
}
+3
source share
2 answers

I think you should try using ListItem. ListItem has the selected property

+1
source

I would say that the easiest way to achieve this is to link the selected element as well ...

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ViewModel="clr-namespace:WpfApplication1.ViewModel"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <ViewModel:NameViewModel></ViewModel:NameViewModel>
</Window.DataContext>
    <Grid>
        <ComboBox 
           Height="23" 
           Width="120" 
           ItemsSource="{Binding Names}" 
           SelectedItem="{Binding SelectedName}"
           />
    </Grid>
</Window>

public class NameViewModel
{
   private IList<string> _nameList = new List<string>();
   public IList<string> Names { get; set; }
   public string SelectedName { get; set; }
   public NameViewModel()
   {
       Names = GetAllNames();
       SelectedName = "A";
   }

   private IList<string> GetAllNames()
   {
       IList<string> names = new List<string>();
       names.Add("A");
       names.Add("B");
       names.Add("C");
       names.Add("D");
       return names;
   }
}
+3
source