Reputation: 347
I populated combobox using an IEnumerable<string>Variables
.
The items are displayed correctly and allows user to select an option.
<ComboBox Grid.Row="0" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center"
x:Name="ofmvar" IsTextSearchEnabled="True" Width="150" Margin="2,2,2,2"
ItemsSource="{Binding Variables}" SelectionChanged="log_SelectionChanged"
SelectedItem="{Binding SelectedVar, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"/>
Most of the time (98%) user selects one specific option from the list; lets call it "A_Variable". but occasionally he may select a different variable from the combobox; lets call it "B_Variable".
When the program launches, he expects the combobox to display "A_Variable" by default as selection.. Is this possible to do?
This is how the SelectedVar
is defined:
public string SelectedVar
{
get { return _SelectedVar; }
set
{
if (_SelectedVar == value) return;
_SelectedVar = value;
OnPropertyChanged("SelectedVar");
}
}
public string _SelectedVar;
Upvotes: 0
Views: 441
Reputation: 169200
Set the value of the SelectedVar
property to "A_Variable" or whatever value in the Variables
collection that you want to select in your view model class:
class ViewModel
{
public ViewModel()
{
Variables = new List<string> { "A_Variable", "B_Variable" };
SelectedVar = "A_Variable"; //default selected value...
}
public IEnumerable<string> Variables { get; private set; }
private string _SelectedVar;
public string SelectedVar
{
get { return _SelectedVar; }
set
{
if (_SelectedVar == value) return;
_SelectedVar = value;
OnPropertyChanged("SelectedVar");
}
}
//...
}
Upvotes: 1
Reputation: 9648
Since the SelectedItem
is bound to SelectedVar
of the ViewModel, just set SelectedVar
to the default value in the constructor of the ViewModel.
Upvotes: 2