wp8弹窗后按返回键取消弹窗

一、首先我们定义一个自定义弹窗类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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值