I want to have the selected index of a combobox change based on code from the ViewModel. Is this possible?
This is how my combobox is set up:
<ComboBox x:Name="cmbModels" DisplayMemberPath="ModelItemTextbox"
SelectedItem="ItemNameTextbox" SelectionChanged="ModelSelectionChange"
ItemsSource="{Binding ModelComboList}">
</ComboBox>
Something else, my bindings don't work unless I have the SelectedItem set to "ItemNameTextbox". The Combobox is binded to an observableCollection.
private ObservableCollection<ModelComboListModel> _modelcombolist = new ObservableCollection<ModelComboListModel>();
public ObservableCollection<ModelComboListModel> ModelComboList
{
get { return _modelcombolist; }
set
{
_modelcombolist = value;
OnPropertyChanged("ModelComboList");
}
}
And the class:
public class ModelComboListModel
{
public string ItemName { get; set; }
public string ItemId { get; set; }
//public override string ToString()
//{
// return $"ID:{ModelItemId} | {ModelItemName}";
//}
public string ItemTextbox
{
get
{
return $"{ ItemId }: {ItemName}";
}
}
}
The list just contains items and their id's.
Is there a good trick for changing the selectedindex from the ViewModel? I can't find anything useful on google or here :(
You probably want to bind to the
SelectedIndexproperty in yourComboBox. Then you can be strategic with yourgets andsets in the view model to get the behavior you are looking for. In this example I made aTextBoxthat can be used to change the index of theComboBox:View Model: