0
我正在使用設計模式MVVM創建一個WPF應用程序,在下一步中,我需要在另一個窗口中使用MainWindow中顯示的DataGrid的內容。 有沒有辦法使用ViewModels傳遞的其他Windows中的特定窗口中創建的項目?在WPF MVVM的其他視圖中使用DataGrid的內容
我正在使用設計模式MVVM創建一個WPF應用程序,在下一步中,我需要在另一個窗口中使用MainWindow中顯示的DataGrid的內容。 有沒有辦法使用ViewModels傳遞的其他Windows中的特定窗口中創建的項目?在WPF MVVM的其他視圖中使用DataGrid的內容
您可以將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 here
另一種方法是使用事件。請任何想要MainViewModel
的數據的Viewmodel
訂閱MainViewModel
用期望的數據調用的事件。
設計使用依賴注入,還是通過事件聚合器進行消息傳遞或更好地在服務中共享內容都不是更好。 – TYY
是的,除非它是一個較小的項目,否則最好使用DI。我只是給出一個如何共享資源的基本示例。 – mrsargent
我將編輯我的帖子以指出。 – mrsargent