I am trying to bind my ComboBox to list of strings and I would like it to show default value once Window is loaded.
To do that, I created a ViewModel class like:
namespace MyData
{
class ViewModel
{
public ViewModel()
{
this.Name = "";
this.Age = 0;
this.Address = "";
this.DateOfPurchase = DateTime.Now.AddDays(-30);
this.CarModel = "VW"; //I want to set VW as default but options are Mazda, VW, Audi
}
public IEnumerable<String> CarModels
{
get
{
var carModels = new String[] {"Mazda", "VW", "Audi"};
//CarModel = cars.FirstOrDefault(car => CarModel == "VW"); //this is not needed
return carModels;
}
}
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public DateTime DateOfPurchase { get; set; }
public String CarModel { get; set; }
}
}
Then I set DataSource of Window to my ViewModel
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = new ViewModel();
}
Finally, I would like to bind my controls to this data. I have done so for all others except my ComboBox. I would like it to get the string array with models (Mazda, VW, and Audi) as its ComboBoxItems and to default to 2nd which is VW once form loads.
Then I bind it like this in my XAML:
<ComboBox Name="cbCarModels" SelectedItem="{Binding CarModel, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding CarModels}">
And this works!