一、首先我们定义一个自定义弹窗类MyMessageBox和自定义控件MyControl
using Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Shapes;
namespace 弹窗Demo
{
class MyMessageBox
{
Popup popup;
public MyMessageBox()
{
//获取当前框架类
var RootFrame = App.RootFrame;
//查找出当前页面类
var page = FindChildOfType<PhoneApplicationPage>(RootFrame);
//当前页面类的返回事件
page.BackKeyPress+=page_BackKeyPress;
}
private void page_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
//判断popup控件是否打开
if (popup.IsOpen)
{
//返回页面属性变成不可返回
e.Cancel = true;
//关闭popup控件
popup.IsOpen = false;
}
}
#region FindChildOfType<T>
//利用递归查找当前父控件类中是否包含该子类,并返回该子类
public T FindChildOfType<T>(DependencyObject root) where T : class
{
var queue = new Queue<DependencyObject>();
queue.Enqueue(root);
while (queue.Count > 0)
{
var current = queue.Dequeue();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++)
{
var child = VisualTreeHelper.GetChild(current, i);
var typeChild = child as T;
if (typeChild != null)
{
return typeChild;
}
else
{
queue.Enqueue(child);
}
}
}
return null;
}
#endregion
//popup弹窗方法
public void Show()
{
popup = new Popup();
StackPanel sp = new StackPanel();
sp.Children.Add(new MyControl());
sp.Children.Add(new Rectangle { Height = 800, Width = 480, Fill = new SolidColorBrush(Colors.Gray), Opacity = 0.5 });
popup.Child = sp;
popup.IsOpen = true;
}
}
}
二、在Page中调用Button控件中德Click事件调用MyMessageBox类的show()方法
此时在弹窗后显示窗体可以按返回键关闭,不会关闭整个Page