在 WPF MVVM 中的其他视图中使用 DataGrid 内容



我正在使用设计模式MVVM制作一个WPF应用程序,在下一步中,我需要在另一个窗口中使用DataGrid的内容,显示在MainWindow中。有没有办法在通过视图模型的其他窗口中使用在特定窗口中创建的项目?

可以将 MainViewModel 作为对其他视图模型的引用传递。 这样,您就可以从其他视图模型访问 MainViewModel 中的数据。

 public class MainViewModel
{
    public AnotherViewModel avm { get; set; }
    public int ImportantInfo { get; set; }
    public MainViewModel()
    {
        avm = new AnotherViewModel(this);
    }
}
public class AnotherViewModel
{
    public MainViewModel mvm { get; set; }
    public AnotherViewModel(MainViewModel mvm)
    {
        this.mvm = mvm;
        MoreImportantINfo = this.mvm.ImportantInfo;
    }
    public int MoreImportantINfo { get; set; }      
}

这种类型的引用只是一个可以在较小项目中使用的示例。 对于较大的项目,通过依赖注入(DI)实现相同的想法。 查看这篇文章 tor 在此处阅读有关 DI 的更多信息

另一种方法是使用事件。 让任何需要来自MainViewModel的数据的Viewmodel订阅MainViewModel使用所需数据调用的事件。

最新更新