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;
由于SelectedItem
已绑定到ViewModel的SelectedVar
,因此只需在ViewModel的构造函数中将SelectedVar
设置为默认值即可。
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");
}
}
//...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.