如何使用App.xaml资源中定义的Popup?

时间:2011-05-13 09:44:14

标签: windows-phone-7

我在App.xaml资源中定义了一个弹出窗口:

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

我想以这种方式使用它:

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

由于某种原因,弹出窗口没有显示? 任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:5)

您的问题是,当您在App.xaml PopUp中定义Resources及其内容时,您将其分配给与您页面上显示的树不同的可视树。将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;

请注意,这样您不再在App的Resource字典中引用它,如果您尝试后续调用此方法,它将因NullReferenceException而失败。再次,通过一些代码,您可以解决此问题,并在关闭它时将PopUp添加回资源:

popup.IsOpen = false; //之前存储的PopUp的本地引用 ContentPanel.Children.Remove(弹出); //从当前可视树中删除 App.Current.Resources.Add(“popup”,popup); //将其添加回资源

尽管此代码有效并且您可以正确显示您的PopUp,但我认为只有PopUp您可以在页面内部实际定义并通过更改{{1}使其可见,这有点过分。属性。