【问题标题】:WPF MVVM Directly accessing object list from ViewModelClassWPF MVVM 从 ViewModelClass 直接访问对象列表
【发布时间】:2021-05-21 06:12:36
【问题描述】:

我的问题可能听起来很傻,但我真的不知道该怎么做,因为它给了我一个错误。所以我在 ObservableCollection 中有一个包含对象的类:

public class UIElementList
{
    public ObservableCollection<ChangingUIElements> ElementList { get; set; }
}

我想像这样从我的 ViewModel 类中直接访问这个类:

private UIElementList uIElementList = new UIElementList();

public UIElementList UIElementList
{
    get => uIElementList.ElementList;
}

但是有些严重的错误,因为编译器给了我一个错误: 错误 CS0029 无法将类型“System.Collections.ObjectModel.ObservableCollection”隐式转换为“PartialResultOperation.Model.UIElementList”

【问题讨论】:

    标签: c# wpf mvvm


    【解决方案1】:

    解决方案:

    private UIElementList uIElementList = new UIElementList();
    public System.Collections.ObjectModel.ObservableCollection<ChangingUIElements> UIElementList2
    {
        get => uIElementList.ElementList;
    }
    
    public class UIElementList
    {
        public System.Collections.ObjectModel.ObservableCollection<ChangingUIElements> ElementList { get; set; }
    }
    

    问题:

    public UIElementList UIElementList
    {
        get => uIElementList.ElementList
    }
    

    在这里你尝试返回一个UIElementList,但uIElementList.ElementList 是一个ObservableCollection。因此这是行不通的。

    您的属性名称也与您的班级名称相同。请避免这种情况(所以不要写 UIElementList UIElementList 任何其他属性名称)。

    或者你也可以使用一种方法:

    public System.Collections.ObjectModel.ObservableCollection<ChangingUIElements> GetUIElementList()
    {
        return uIElementList.ElementList;
    }
    

    【讨论】:

    • 非常感谢,它就像一个魅力! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2016-08-12
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    相关资源
    最近更新 更多