2011-05-13 30 views
3

我在App.xaml資源中定義了一個彈出窗口:如何使用App.xaml資源中定義的Popup?

<Application.Resources> 
     <Popup x:Key="popup"> 
      //some content here 
     </Popup> 
    </Application.Resources> 

我想以這種方式使用它:

     Popup popup = this.Resources["popup"] as Popup; 
        popup.IsOpen = true; 

出於某種原因,彈出窗口沒有顯示? 非常感謝任何幫助。

回答

5

您的問題是,當您在App.xaml Resources中定義PopUp及其內容時,您將其分配給與頁面上顯示的不同的可視化樹。將IsOpen屬性設置爲true作品不足以使其可見,但必須將PopUp添加到當前的可視化樹中。 這是第二個問題,因爲PopUp已經有Parent,您不能直接將它添加到您的頁面,因爲您會得到一個InvalidOperationException

這裏是一個可能的解決方案:

popup = App.Current.Resources["popup"] as Popup; 
App.Current.Resources.Remove("popup"); // remove the PopUp from the Resource and thus clear his Parent property 
ContentPanel.Children.Add(popup);  // add the PopUp to a container inside your page visual tree 
popup.IsOpen = true; 

要注意的是這種方式,您不再有其參考您的應用程序的資源字典裏面,如果你嘗試這種方法的後續調用會因無法一個NullReferenceException 。再次,使用一點代碼,您可以修復此問題並在關閉時將PopUp添加回資源:

popup.IsOpen = false; //本地引用您之前存儲的PopUp ContentPanel.Children.Remove(popup); //從當前可視化樹中移除 App.Current.Resources.Add(「popup」,popup); //將其添加回資源

儘管此代碼可以正常工作,並且您可以讓PopUp正確顯示,但我認爲這對於PopUp來說有點矯枉過正,您可以在頁面中實際定義並通過更改IsOpen屬性。

+0

謝謝你的幫助。 – 2011-05-13 16:00:12

相關問題