我正在編寫一個使用MEF和第三方庫MEFedMVVM的WPF應用程序。使用MEFedMVVM在父視圖/視圖模型中實現視圖模型優先方法
我試圖創建一個設計,從而父視圖模型有一個子視圖模型的集合,我希望使用視圖模型優先的方法,因爲這保持視圖模型以外的視圖,從而保持代碼更多視圖以模型爲中心,更多單元可測試。
我已閱讀this discussion和this discussion關於使用DataTemplate進行視圖以及Reed Copsy,Jr的建議here使用通用視圖來查看模型映射資源。但是,我正在努力實現一些有效的工作。
我父母的看法是非常簡單的:
[ExportViewModel("MyParentViewModel")]
public class MyParentViewModel : ViewModelBase
{
[ImportingConstructor]
public MyParentViewModel()
{
var myChildVM = ServiceLocator.Current.GetInstance<MyChildViewModel>());
}
}
這是孩子視圖模型:
<UserControl x:Class="MyParentView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:meffed="clr-namespace:MEFedMVVM.ViewModelLocator;assembly=MEFedMVVM.WPF"
meffed:ViewModelLocator.ViewModel="MyParentViewModel" />
父視圖模型從實現IContextAware基類型派生
[Export(typeof(MyChildViewModel))]
[ExportViewModel("MyChildViewModel", true)]
public class MyChildViewModel : ViewModelBase
{
}
而這有一個相應的視圖:
<UserControl x:Class="MyChildView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:meffed="clr-namespace:MEFedMVVM.ViewModelLocator;assembly=MEFedMVVM.WPF"
meffed:ViewModelLocator.ViewModel="MyChildViewModel" />
起初,我還以爲指定的ExportViewModel屬性的第二個布爾參數MyChildViewModel將使用視圖模型,第一種方法使一切工作爲我的觀點和看法車型在視圖MEFed在一起'XAML代碼。然而,事實證明這是不是這樣的,什麼我居然得到傳遞給IContextAware.InjectContext()當我在MyParentViewModel構造函數實例化一個MyChildViewModel對象是MyParentView對象。不是我期待和希望的對象。顯然,我需要添加一些東西來將它們連接起來。任何人都可以提供一個如何做到這一點的例子嗎?
謝謝!
是有一個原因,你正在使用一個服務定位,讓您的孩子VM?爲什麼不用MEF呢? – 2012-04-26 19:23:49
爲什麼'MyChildView'指定'ViewModel =「MyParentViewModel」'? – 2012-04-26 19:25:19
謝謝jberger,愚蠢的錯字 - 已經糾正它。 – Neo 2012-04-30 08:45:10