簡體   English   中英

在WPF MVVM的其他視圖中使用DataGrid內容

[英]Using DataGrid content in other View in WPF MVVM

我正在使用設計模式MVVM制作WPF應用程序,在下一步中,我需要使用另一個窗口中MainWindow中顯示的DataGrid的內容。 有沒有一種方法可以使用ViewModels在其他Windows中在特定Window中創建的項目?

您可以傳遞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)實現相同的想法。 在這篇文章中查看更多關於DI的信息

另一種方法是使用事件。 讓需要MainViewModel數據的任何Viewmodel訂閱MainViewModel調用所需數據的事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM