- Default value: If you set
viewModel.Car = "VW" , then it should automatically select this item in the combo box. To do this, you need to either implement INotifyPropertyChanged or install Car before setting the DataContext .
Running INotifyPropertyChanged might look like this:
class ViewModel : INotifyPropertyChanged { private string car; public ViewModel() { this.Car = "VW"; this.Cars = new ObservableCollection<string>() { "Mazda", "VW", "Audi" }; } public string Car { get { return this.car; } set { if (this.car != value) { this.car = value; OnPropertyChanged(); } } } public ObservableCollection<string> Cars { get; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
2. Bind ItemsSource and SelectedItem .
<ComboBox ItemsSource="{Binding Cars}" SelectedItem="{Binding Car, Mode=TwoWay}"> </ComboBox>
You can also set ComboBox.ItemTemplate if your source or view is more complex than just displaying a string:
<ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </ComboBox.ItemTemplate>
In the view model, just add a list property:
public ObservableCollection<string> Cars { get; set; }
It should not be an ObservableCollection , but this type will automatically update the user interface every time the collection changes.
source share