简体   繁体   中英

Default load up value in ComboBox - WPF MVVM

I have a ComboBox and want to prepopulate the value in the ComboBox to a preset value.

I have a list of food categories, which is an ObservableCollection called ItemCategories , which is a property. The list has 5 different types.

I also have a selected category property called ItemCategory of type ItemCategory.

ItemCategory has two properties, Category and PK_ItemCategoryId.

So far this is what I have

ComboBox XAML

ComboBox Contents RunTime

The combobox's ItemSource is bound to a property in the ViewModel.

private ObservableCollection<ItemCategory> _itemCategories;
        public ObservableCollection<ItemCategory> ItemCategories
        {
            get
            { return _itemCategories; }
            set
            {
                _itemCategories = value;
                OnPropertyChanged("ItemCategories");
            }
        }

        private ItemCategory _itemCategory;
        public ItemCategory ItemCategory
        {
            get { return _itemCategory; }
            set
            {
                _itemCategory = value;
                OnPropertyChanged("ItemCategory");
            }
        }

What I want to do, when the user opens the app is to prepopulate the value in the combox witha an item in the list. Below is an example what I want to achieve.

Goal

How can I acheive this using MVVM and WPF?

It should work if you set the default item (eg first item of _itemCategories) to _itemCategory in ctor of the ViewModel or later on over your ItemCategory property.

It has to be one of the items from _itemsCategories - NOT a new instance of ItemCategory!

Since your SelectedItem property is set to Mode=TwoWay , you can set the property in your ViewModel like this:

//if you imported LINQ
if(ItemCategories != null && ItemCategories.Any())
    ItemCategory = ItemCategories.First();

//without LINQ
if(ItemCategories != null && ItemCategories.Count > 0)
    ItemCategory = ItemCategories[0];

This would take the first item in ItemCategories , if there is any, and set it as the SelectedItem .

The UI will be notified through OnPropertyChanged() .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM