Is this the correct way to bind ComboBox?

2019-08-31 14:07发布

My binding is showing me the values perfectly. But I just want to be sure that I learn the technology in its right direction. I want to follow MVVM pattern.

Here is my code for viewModel:

class MainPageViewModel 
{
    public MainPageViewModel()
    {
        using (Lab_Lite_Entities db = new Lab_Lite_Entities())
        {
            Sex = (from t in db.TypeSexes
                   select t.Value).ToList();
        }
    }

    public List<string> Sex
    {
        get;
        private set;
    }
}

Here are my tables:

Persons table:

ID
Name
SexID 
Age

Sex table:

SexID
Value

标签: c# wpf mvvm
1条回答
虎瘦雄心在
2楼-- · 2019-08-31 14:41

Short answer: Yes.

Long answer: Kinda.

What you have here is only half the stuff you need in order to bind your combobox to the List. You should have your XAML that will look like :

<Combobox ItemSource={Binding Sex} ... />

which is what will actually bind the combobox to the collection (list in your case).

Usually, the suggestion is to bind to an Observable collection, but since I don't see how your Sex table might change all of the sudden, it's not a big issue and binding the list should work as well.

Also, you should have your datacontext set. Either globally on the view, or specifically on the combobox. Most MVVM framework will give you some help with a locator of some sort.

查看更多
登录 后发表回答