繁体   English   中英

ComboBox中的默认加载值-WPF MVVM

[英]Default load up value in ComboBox - WPF MVVM

我有一个ComboBox,想将ComboBox中的值预先填充为预设值。

我有一个食物类别列表,它是一个名为ItemCategories的ObservableCollection,它是一个属性。 列表有5种不同的类型。

我还有一个名为ItemCategory的选定类别属性,类型为ItemCategory。

ItemCategory具有两个属性,Category和PK_ItemCategoryId。

到目前为止,这就是我所拥有的

ComboBox XAML

ComboBox内容运行时

组合框的ItemSource绑定到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");
            }
        }

当用户打开应用程序时,我想做的是用列表中的一个项目预填充combox中的值。 以下是我要实现的示例。

目标

如何使用MVVM和WPF实现此目的?

如果您在ViewModel的ctor中将默认项(例如_itemCategories的第一项)设置为_itemCategory,则应该工作,或者稍后在ItemCategory属性上将其设置为_itemCategory。

它必须是_itemsCategories中的项之一-不是ItemCategory的新实例!

由于您的SelectedItem属性设置为Mode=TwoWay ,因此您可以像这样在ViewModel设置该属性:

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

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

如果有的话,它将采用ItemCategories的第一个项目,并将其设置为SelectedItem

UI将通过OnPropertyChanged()通知。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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