在WPF MVVM应用程序中的ComboBox中设置默认选定项目 [英] Setting a default selected item in ComboBox in WPF MVVM application
问题描述
我一直困扰这个问题数小时...我想做的是其实很简单 - 在ComboBox中设置一个默认的选择项(我使用MVVM模式)。
I've been stuck on this problem for hours... what I want to do is actually quite simple - set a default selected item in a ComboBox (I'm using the MVVM pattern).
我在我的视图中有ComboBox的XAML:
I have the following XAML for the ComboBox in my View:
<ComboBox ItemsSource="{Binding Schools}"
DisplayMemberPath="Acronym"
SelectedValue="{Binding SelectedSchool}"
SelectedValuePath="Id"
/>
在我的ViewModel中,我有一个ObservableCollection,Schools:
In my ViewModel, I have an ObservableCollection, Schools:
public ObservableCollection<School> Schools { get; private set; }
public CourseFormViewModel()
{
Schools = new ObservableCollection<School>();
try
{
// Gets schools from a web service and adds them to the Schools ObservableCollection
PopulateSchools();
}
catch (Exception ex)
{
// ...
}
}
public int SelectedSchool
{
get { return schoolId; }
set
{
schoolId = value;
OnPropertyChanged("SelectedSchool");
}
}
最后,School是一个简单的业务对象: p>
Finally, School is a simple business object:
[DataContract]
public class School
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Acronym { get; set; }
[DataMember]
public string Name { get; set; }
}
问题是,当应用程序启动时,组合框不会得到默认值。我试过在XAML中将SelectedIndex设置为0,但没有效果。我试过在一个Window_Loaded事件处理程序中设置SelectedIndex代码隐藏(这是工作),但因为我使用MVVM模式感觉脏。我仍然是新的整个WPF / MVVM的东西,所以如果有人可以指出我的方向,我会感激。
The problem is, that when the application is started, the combobox does not get a default value. I've tried setting the SelectedIndex to 0 in XAML, but to no avail. I've tried setting the SelectedIndex in a Window_Loaded event handler in the code-behind (which works), but since I'm using the MVVM pattern that feels kind of dirty. I'm still new to this whole WPF/MVVM stuff, so if someone could point me in the right direction I would be grateful.
推荐答案
您可以像这样设置SelectedSchool:
You can set SelectedSchool like this:
public void CourseFormViewModel()
{
Schools = new ObservableCollection<School>();
try
{
// Gets schools from a web service and adds them to the Schools ObservableCollection
PopulateSchools();
SelectedSchool = 3;
}
catch (Exception ex)
{
// ...
}
}
测试数据:
Schools.Add(new School { Id = 1, Name = "aaa", Acronym = "a" });
Schools.Add(new School { Id = 2, Name = "bbb", Acronym = "b" });
Schools.Add(new School { Id = 3, Name = "ccc", Acronym = "c" });
您将获得所选项目c。
如果你想使用最小的Id的init ComboBox,你可以使用这个代码:
If you want init ComboBox with the smallest Id you can use this code:
SelectedSchool = Schools.Min(x => x.Id);
而不是分配常量值。
这篇关于在WPF MVVM应用程序中的ComboBox中设置默认选定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!