【问题标题】:Default load up value in ComboBox - WPF MVVMComboBox 中的默认加载值 - WPF MVVM
【发布时间】:2018-09-23 14:41:00
【问题描述】:

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

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

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

ItemCategory 有两个属性,Category 和 PK_ItemCategoryId。

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

ComboBox XAML

ComboBox Contents RunTime

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

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

Goal

如何使用 MVVM 和 WPF 实现这一目标?

【问题讨论】:

    标签: c# wpf xaml mvvm combobox


    【解决方案1】:

    由于您的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() 得到通知。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-05-23
        • 1970-01-01
        • 2020-08-26
        • 1970-01-01
        • 2015-07-09
        • 2012-06-19
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        相关资源
        最近更新 更多