[英]How do I use Dependency Injection between a Core project and a WPF application with changing pages?
我正在使用MVVM
Framework以及Dependancy Injection
Ninject
構建WPF
程序。 我創建了兩個項目,一個用於與其他.Net
應用程序一起使用的.Net Class Library
核心項目,以及一個WPF
特定應用程序。
目前,我正在使用具有Property
CurrentPage
的ApplicationViewModel
更改應用程序的頁面。 CurrentPage
是一個名為ApplicationPage
的Enum
類型,其中包含ApplicationPage
中的不同頁面。 在我的WPF應用程序的MainWindow中是一個框架,其Content
bound
到CurrentPage Property
並使用值轉換器將值轉換為我使用switch
語句制作的不同CustomPages
,如下所示:
if (value is ApplicationPage)
switch ((ApplicationPage)value)
{
case ApplicationPage.PageOne:
return new PageOne();
case ApplicationPage.PageTwo:
return new PageTwo();
default:
throw Exception;
}
}
我想使用Constructor
Injection
將這些頁面的View Models
傳遞到Converter
內的Page's
Constructor
中,使用依次Injected
到ApplicationViewModel
類中的ViewModels
,就像這樣:
case ApplicationPage.PageOne:
return new PageOne(PageOneViewModel);
我的第一個想法是,是否有某種方法可以使CurrentPage
Property
實際上是特定的ViewModel
並在哪個ViewModel
上執行switch
,以便Converter
將ViewModel
轉換為Page
?
但是, CurrentPage
的類型是一個問題,因為必須將其設置為ViewModels
,因此不能采用其他ViewModel
的值,從而使您只能使用一個ViewModel
Class
。
我的想法是:是否可以將ViewModel
傳遞給Converter
? 還是可以將CurrentPage
設置為IViewModelFactory
並在工廠的轉換器中創建ViewModel
? 在那種情況下,如何更改CurrentPage
的值以更改應用程序中的頁面?
在遵循此邏輯的同時,有沒有辦法堅持Dependency
Injection
,還是有另一種辦法,我是否需要重新考慮我的代碼以進行頁面更改? 不幸的是,我看到的大多數示例都屬於所謂的ServiceLocator
反模式。
答案是使用如下數據模板,
<Window.Resources>
<DataTemplate x:Key="View1Template" DataType="{x:Type local:MainWindowViewModel}">
<!-- Custom control style with a Data Context set to a Viewmodel
object in the MainWindowViewModel -->
<local:CustomPage1 DataContext="{Binding CustomPage1ViewModel}" />
</DataTemplate>
<DataTemplate x:Key="View2Template" DataType="{x:Type local:MainWindowViewModel}">
<!-- Custom control style with a Data Context set to a Viewmodel
object in the MainWindowViewModel -->
<local:CustomPage2 DataContext="{Binding CustomPage2ViewModel}" />
</DataTemplate>
</Window.Resources>
然后在Content Control Style
設置Data Trigger
;
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<!-- The Default/initial View being shown -->
<Setter Property="ContentTemplate" Value="{StaticResource View1Template}" />
<!-- Triggers bound to the CurrentView Property -->
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentView}" Value="1">
<Setter Property="ContentTemplate" Value="{StaticResource View1Template}" />
</DataTrigger>
<DataTrigger Binding="{Binding CurrentView}" Value="2">
<Setter Property="ContentTemplate" Value="{StaticResource View2Template}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
CurrentView
是可以在代碼中更改以Trigger
UI
更改的屬性-可以設置為PageNames
的Enum
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.