這是很好的做法,不僅使用SOLID設計原則,建立你的ViewModels,但要做到這一點在你的意見也。 usercontrols的使用可以幫助你做到這一點。
如果技術上可行,建議方法的缺點是該設計將違反SRP和OCP。
SRP,因爲您的用戶控件需要的所有依賴項必須注入消費窗口/視圖中,而此視圖可能不需要(全部)這些依賴項。
而OCP因爲每一個你添加或刪除你的用戶控件的依賴,你還需要添加或從消費窗口/視圖中刪除它。
有了你能組成的觀點,就像您撰寫的其他類,如服務,命令 - 和queryhandlers等。當涉及到依賴注入的地方構成您的應用程序用戶控件是composition root
WPF中的ContentControls都是關於從應用程序中的其他「內容」'構成'你的觀點。
像Caliburn Micro這樣的MVVM工具通常使用contentcontrols通過它自己的viewmodel注入一個usercontrol視圖(讀取:無代碼的xaml)。事實上,在使用MVVM時,您應該從usercontrols類構建應用程序中的所有視圖,這是最佳做法。
這可能是這個樣子:
public interface IViewModel<T> { }
public class MainViewModel : IViewModel<Someclass>
{
public MainViewModel(IViewModel<SomeOtherClass> userControlViewModel)
{
this.UserControlViewModel = userControlViewModel;
}
public IViewModel<SomeOtherClass> UserControlViewModel { get; private set; }
}
public class UserControlViewModel : IViewModel<SomeOtherClass>
{
private readonly ISomeService someDependency;
public UserControlViewModel(ISomeService someDependency)
{
this.someDependency = someDependency;
}
}
而XAML爲的MainView:
// MainView
<UserControl x:Class="WpfUserControlTest.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<ContentControl Name="UserControlViewModel" />
</Grid>
</UserControl>
// UserControl View
<UserControl x:Class="WpfUserControlTest.UserControlView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<TextBlock Text="SomeInformation"/>
</Grid>
</UserControl>
其結果將是,該MainView
顯示在一個窗口,在該窗口的DataContext
設置爲MainViewModel
。內容控件將填充UserControlView
,其DataContext
設置爲UserControlViewModel
類。這會自動發生,因爲MVVM工具將使用Convention over configuration將視圖模型綁定到相應的視圖。
如果您不使用MVVM工具,而是直接將您的依賴關係注入窗口類的代碼後面,則可以使用相同的模式。在視圖中使用ContentControl,就像上面的例子一樣,並在窗口的構造函數中注入UserControl
(帶有一個包含所需參數的構造函數)。然後,只需將ContentControl的Content
屬性設置爲UserControl的注入實例。
這將是這樣的:
public partial class MainWindow : Window
{
public MainWindow(YourUserControl userControl)
{
InitializeComponent();
// assuming you have a contentcontrol named 'UserControlViewModel'
this.UserControlViewModel.Content = userControl;
}
// other code...
}
請參閱集成指南[這裏](https://simpleinjector.readthedocs.org/en/latest/wpfintegration.html) – qujck
我看到了。但它解決了我的意圖嗎?其實我有第二個窗口我想填充。但是由於我無法從XAML實例化控件,我是否必須放棄我的XAML? (因爲缺少0-ctor) – Robetto
你有一些不工作的代碼,或者這是一個理論問題嗎? – qujck