2010-03-27 78 views
2

我有一個WPF應用程序,我想創建一個具有模態行爲的自定義彈出窗口。我已經能夠使用相當於「DoEvents」的解決方案來破解解決方案,但有沒有更好的方法來做到這一點?這是我目前所擁有的:WPF中的自定義模態窗口?

private void ShowModalHost(FrameworkElement element) 
    { 
     //Create new modal host 
     var host = new ModalHost(element); 

     //Lock out UI with blur 
     WindowSurface.Effect = new BlurEffect(); 
     ModalSurface.IsHitTestVisible = true; 

     //Display control in modal surface 
     ModalSurface.Children.Add(host); 

     //Block until ModalHost is done 
     while (ModalSurface.IsHitTestVisible) 
     { 
      DoEvents(); 
     } 
    } 

    private void DoEvents() 
    { 
     var frame = new DispatcherFrame(); 
     Dispatcher.BeginInvoke(DispatcherPriority.Background, 
      new DispatcherOperationCallback(ExitFrame), frame); 
     Dispatcher.PushFrame(frame);    
    } 

    private object ExitFrame(object f) 
    { 
     ((DispatcherFrame)f).Continue = false; 

     return null; 
    } 

    public void CloseModal() 
    { 
     //Remove any controls from the modal surface and make UI available again 
     ModalSurface.Children.Clear(); 
     ModalSurface.IsHitTestVisible = false; 
     WindowSurface.Effect = null; 
    } 

我的ModalHost是一個用戶控件,用於託管另一個具有動畫和其他支持的元素。

+0

是的,這是應該如何完成的。除此之外,你可能不需要IsHitTestVisible循環。 – Ray

+0

該循環是什麼使ShowModalHost呼叫阻塞;否則它將在ModalHost關閉之前返回到原始調用上下文。 –

回答

2

我會推薦重新考慮這個設計。

在某些情況下使用「DoEvents」會導致一些非常奇怪的行爲,因爲您允許代碼在試圖同時阻止的情況下運行。

除了使用彈出窗口外,還可以考慮使用帶有ShowDialog的窗口,只需適當地設置它即可。這將是實現模態行爲的「標準」方式,WPF讓你設計一個窗口,使其看起來像一個彈出窗口,非常容易......

+0

謝謝,這效果更好。重新調整的窗口給了我想要的模態行爲,並且我仍然可以靈活地獲得我之後的視覺效果。這讓我擺脫了ModalSurface及其關聯的入侵,以阻止點擊底層窗口。 –