WPF弹出带蒙板的消息框

效果图

 

思路

拿到父级窗体的内容,放入一个容器里,再在容器里放入一个半透明层.将整个容器赋给父级窗体的内容.

关闭时反向操作.

 

 代码

消息窗弹出时

 1 /// <summary>
 2 /// 弹出消息框
 3 /// </summary>
 4 /// <param name="message">消息</param>
 5 /// <param name="owner">父级窗体</param>
 6 public static void ShowDialog(string message, Window owner)
 7 {
 8     //蒙板
 9     Grid layer = new Grid() { Background = new SolidColorBrush(Color.FromArgb(128, 0, 0, 0)) };
10     //父级窗体原来的内容
11     UIElement original = owner.Content as UIElement;
12     owner.Content = null;
13     //容器Grid
14     Grid container = new Grid();
15     container.Children.Add(original);//放入原来的内容
16     container.Children.Add(layer);//在上面放一层蒙板
17     //将装有原来内容和蒙板的容器赋给父级窗体
18     owner.Content = container;
19 
20     //弹出消息框
21     MessageBox box = new MessageBox() { Owner = owner };
22     box.tbc_message.Text = message;
23     box.ShowDialog();
24 }

消息框关闭时

 1 /// <summary>
 2 /// 窗体关闭事件
 3 /// </summary>
 4 private void Window_Closed(object sender, EventArgs e)
 5 {
 6     //容器Grid
 7     Grid grid = this.Owner.Content as Grid;
 8     //父级窗体原来的内容
 9     UIElement original = VisualTreeHelper.GetChild(grid, 0) as UIElement;
10     //将父级窗体原来的内容在容器Grid中移除
11     grid.Children.Remove(original);
12     //赋给父级窗体
13     this.Owner.Content = original;
14 }

源码下载:MessageBoxWithLayer.zip

posted @ 2016-12-22 17:38  普通的地球人  阅读(10188)  评论(8编辑  收藏  举报