簡體   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