[英]How to display “default” selected item - Combobox C# WPF
I populated combobox using an IEnumerable<string>Variables
. 我使用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; 大多数情况下(98%)用户从列表中选择一个特定选项。 lets call it "A_Variable". 让我们称之为“ A_Variable”。 but occasionally he may select a different variable from the combobox; 但有时他可能会从组合框中选择其他变量; lets call it "B_Variable" . 让我们称其为“ B_Variable” 。
When the program launches, he expects the combobox to display "A_Variable" by default as selection.. Is this possible to do? 程序启动时,他希望组合框默认显示为“ A_Variable” 。这可能吗?
This is how the SelectedVar
is defined: 这是SelectedVar
的定义方式:
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: 将SelectedVar
属性的值设置为“ A_Variable”或要在视图模型类中选择的Variables
集合中的任何值:
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");
}
}
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.