2012-04-19 21 views
4

我已經閱讀了WPF(以及一般的圖形用戶界面)的一個很好的實踐,說盡可能少的窗口打開。但有時候,你根本沒有選擇。如何使用WPF打開一個尊重良好實踐的新窗口?

所以我想到了一個快速的優雅的解決方案,以打開一個新的窗口,我認爲是這樣的:

public static class WinManager 
{ 
    private static Dictionary<Type, Func<Window>> collection 
     = new Dictionary<Type, Func<Window>>(); 

    /* Bind the type of the ViewModel with a lambda that build an 
    * instance of a window*/ 
    public static void Bind(Func<Window> ctor, Type type) { ... } 

    /* Search in the dictionary the specified type and show the window 
    * returned by the lambda*/ 
    public static void Show(Type type){ ... } 

    /* Search in the dictionary the specified type and show the dialogue 
    * returned by the lambda*/ 
    public static void ShowDialog(Type type) { ... } 
} 

type是視圖模型的綁定到視圖(這是窗口)和拉姆達類型ctor用於返回窗口的新實例。

管理這樣的窗口是個好主意還是我完全錯了?

+0

關於用戶體驗或關於在WPF(以及一般GUI)中處理Windows的最佳實踐是否談論?作爲最終用戶,我寧願使用較少的窗口工作。如果它關於用戶體驗,那麼我認爲你應該解決它的要求,而不是代碼。 – Ramesh 2012-04-19 09:28:26

+0

問題是關於從ViewModel在MVVM中打開Windows,該ViewModel應該是View不可知的。 – 2012-04-19 09:31:51

+2

只是不使用靜態助手,在視圖模型構造函數中將這些東西作爲服務注入。這將爲您節省大量時間編寫單元測試。 – v00d00 2012-04-19 10:11:25

回答

2

我認爲這是一個體面的想法。

它的優點是,想要顯示另一個窗口的ViewModel不必使用任何WPF特定的代碼,甚至不需要知道該視圖。它只需要知道它想要顯示窗口的ViewModel。這與Caliburn.MicrosIWindowManager非常相似。

我不喜歡這個解決方案的東西是這個類的靜態特性。這使得單元測試很難(er)。如果您正在使用依賴注入,您可以創建一個類似於您的靜態類的接口和該接口的實現。然後,您可以在組合根中創建該類的實例,將ViewModel類型綁定到lambda View工廠,並將該實例註冊到DI容器中。現在每個想要顯示另一個窗口的ViewModel都具有對該接口的依賴,這使得它在單元測試中很容易被模擬。

事情是這樣的:

interface IWindowManager 
{ 
    void Show(Type type); 
    void Show<T>(); 
    void ShowDialog(Type type); 
    void ShowDialog<T>(); 
} 

class WindowManager : IWindowManager 
{ 
    // Implementation of the four methods from the interface plus: 

    private Dictionary<Type, Func<Window>> collection 
     = new Dictionary<Type, Func<Window>>(); 

    public void Bind(Func<Window> ctor, Type type) { ... } 
} 

具有Bind方法只對具體的實施WindowManager具有的IWindowManager消費者無法變更登記的好處。

+0

感謝您的反饋。我將避免使用靜態幫助器,並通過ctor或屬性注入實例。 – 2012-04-19 11:32:06

2

這不是壞主意,其實我我的個人項目中所使用的相同,它工作得很好:)

WindowManager,你可以跟蹤顯示在屏幕上所有打開的形式,管理它們的外觀和視覺關係(隱藏一個,如果另一個隱藏太多,像這樣的東西)。