I am trying to bind my ComboBox to a list of strings, and I would like it to display the default value after loading Window.
To do this, I created a ViewModel class, for example:
namespace MyData { class ViewModel { public ViewModel() { this.Name = ""; this.Age = 0; this.Address = ""; this.DateOfPurchase = DateTime.Now.AddDays(-30); this.CarModel = "VW";
Then I installed the DataSource Window in 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 did it for everyone else except my ComboBox. I would like for him to get an array of strings with models (Mazda, VW and Audi) as his ComboBoxItems, and by default be the second one, which is VW, once generates loads.
Then I bind it the same way in my XAML:
<ComboBox Name="cbCarModels" SelectedItem="{Binding CarModel, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding CarModels}">
And it works!
source share