您的問題是,當您在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
屬性。
謝謝你的幫助。 – 2011-05-13 16:00:12