开发者

How to use Popup defined in App.xaml Resources?

开发者 https://www.devze.com 2023-03-06 03:30 出处:网络
I have a popup define开发者_高级运维d inside App.xaml resources: <Application.Resources> <Popup x:Key=\"popup\">

I have a popup define开发者_高级运维d inside App.xaml resources:

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

I want to use it in this way:

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

For some reason the popup does not show? Any help is highly appreciated.


Your problem is, when you define the PopUp and its contents inside App.xaml Resources, you are assigning it to a visual tree different from the one displayed on your page. Setting the IsOpen property to true works is not enough to actually make it visible, you have to add the PopUp to the current visual tree. Here comes your second problem, since the PopUp already has a Parent, you can't add it directly to your page because you would get an InvalidOperationException.

Here's a possible solution:

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;

Beware that this way you no longer have its reference inside the Resource dictionary of your App and if you try a subsequent call to this method it will fail due to a NullReferenceException. Again, with a little bit of code, you can fix this and add the PopUp back to the Resources when you close it:

popup.IsOpen = false; // local reference to your PopUp stored before ContentPanel.Children.Remove(popup); // remove from the current visual tree App.Current.Resources.Add("popup", popup); // add it back to Resources

Although this code works and you can have your PopUp displayed correctly, i think it's a bit of an overkill just for a PopUp you can actually define inside your page and simply make it visible by changing the IsOpen property.

0

精彩评论

暂无评论...
验证码 换一张
取 消