在 WPF MVVM 应用程序的 ComboBox 中设置默认选定项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13791184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:32:50  来源:igfitidea点击:

Setting a default selected item in ComboBox in WPF MVVM application

c#wpfmvvmcombobox

提问by William

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 中设置一个默认的选定项目(我使用的是 MVVM 模式)。

I have the following XAML for the ComboBox in my View:

我的视图中有 ComboBox 的以下 XAML:

<ComboBox ItemsSource="{Binding Schools}" 
          DisplayMemberPath="Acronym" 
          SelectedValue="{Binding SelectedSchool}" 
          SelectedValuePath="Id" 
/>

In my ViewModel, I have an ObservableCollection, Schools:

在我的 ViewModel 中,我有一个 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");
        }
    }

Finally, School is a simple business object:

最后,School 是一个简单的业务对象:

[DataContract]
public class School
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string Acronym { get; set; }
    [DataMember]
    public string Name { get; set; }
}

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.

问题是,当应用程序启动时,组合框没有获得默认值。我尝试在 XAML 中将 SelectedIndex 设置为 0,但无济于事。我已经尝试在代码隐藏(有效)的 Window_Loaded 事件处理程序中设置 SelectedIndex,但因为我使用的 MVVM 模式感觉有点脏。我对整个 WPF/MVVM 的东西还是个新手,所以如果有人能指出我正确的方向,我将不胜感激。

回答by kmatyaszek

You can set SelectedSchool like this:

您可以像这样设置 SelectedSchool:

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)
        {
            // ...
        }
    }

Test data:

测试数据:

 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" });

And you will get selected item "c".

您将获得选定的项目“c”。

If you want init ComboBox with the smallest Id you can use this code:

如果您想要具有最小 Id 的 init ComboBox,您可以使用以下代码:

SelectedSchool = Schools.Min(x => x.Id);

Instead of assign constant value.

而不是分配常数值。