c# - 如何通过 View 模型库访问所有 View 模型?

标签 c# wpf mvvm

我创建了一个ViewModel类,该类在INotifyPropertyChanged的实现内部,现在我还具有从ViewModel(基础)继承的其他ViewModel。
所有的工作实际上都很好,但我对此表示怀疑。
假设我们在CustomerViewModel中有一个名为Price的ObservableCollection,如下所示:

private ObservableCollection<Models.Price> _price = new ObservableCollection<Models.Price>();
public ObservableCollection<Models.Price> Price
{
     get { return _price; }
}

这个ObservableCollection应该由其他类填充,因为我需要访问相同的资源。

我真的不明白如何在mvvm中做到这一点。我虽然使用了Singleton ViewModel,但在基本VM中定义了以下内容:
 public static ViewModel Instance { get; set; }

因此,将所有子VM导入基础库,然后通过ViewModel.Instance.Price;对其进行访问;

但对我来说似乎不是一个好习惯。任何的想法?

最佳答案

通过此实现,您可以将相同的数据源共享给所有ViewModel。

public class PriceGenerator {

        private PriceGenerator() {
            this.Prices = new ObservableCollection<Price>();
            this.Generate();

        }

        void Generate() {
            //Generate Objects here

            this.Prices.Add(generatedPrice);
        }

        public ObservableCollection<Price> Prices {
            get;
        }


        private static PriceGenerator _instance;
        public static PriceGenerator Instance => _instance ?? (_instance = new PriceGenerator());

    }

关于c# - 如何通过 View 模型库访问所有 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38040903/

相关文章:

c# - DataGridView 行在提交更改后仍然是脏的

c# - Winform变得不响应,异步编程,C#

c# - 从现有 View 模型访问 View 模型的正确方法

c# - 在WinRT MVVM中无法执行按钮单击和组合框选择更改

c# - 设置自定义异常的消息而不将其传递给基本构造函数

c# - "DataTable already belongs to another DataSet"

具有自定义下拉宽度的 WPF ComboBox

wpf - 尝试使用 python 3.4 o VS2013 Express 运行 WPF 时出现 "No module named wpf"

c# - 使用 Message.Attach 时 Caliburn.Micro 和/或 WindowsBase 中出现 NullReferenceException

android - 后台线程或非 UI 组件中的 LiveData