如何将WPF窗口用作消息框?

4
我已经创建了一个带有一些样式的小窗口。现在我想要像使用MessageBox一样使用它。我该如何实现?
编辑:我是WPF的新手。我尝试在主窗口中这样调用它。
Window1 messageBox = new Window1();
messageBox.Show();
messageBox.Activate();

问题是新生成的窗口会在主窗口后面消失,导致我无法在其中单击操作按钮。
1个回答

7

使用ShowDialog方法代替Show方法弹出消息框窗口。这样用户就必须先关闭弹出窗口或消息框窗口,然后才能返回主窗口。

 MessageWindow message= new MessageWindow();
 message.ShowDialog();

编辑

显然,您希望在主窗口中返回结果,对吧?有几种简单的方法可以实现。其中一种最简单的方法是在MainWindow中公开一个公共方法。

public GetResult(bool result)
{
   //your logic
} 

创建一个以MainWindow为参数的MessageWindow构造函数。
 private MainWindow window;
 public MessageWindow(MainWindow mainWindow)
        {
            InitializeComponent();
            window = mainWindow;
        }
   //now handle the click event of yes and no button
  private void YesButton_Click(object sender, RoutedEventArgs e)
        { 
            //close this window
            this.Close();
            //pass true in case of yes
            window.GetResult(true);
        }

        private void NoButton_Click_1(object sender, RoutedEventArgs e)
        {
            //close this window
            this.Close();
            //pass false in case of no
            window.GetResult(false);
        }
 //in that case you will show the popup window like this
 MessageWindow message= new MessageWindow(this);
 message.ShowDialog();

谢谢,帮了我很多。我在对话框中有“是”和“否”按钮,如何检索值并应用逻辑?如果 messageBox布尔值=1 做这个 否则 做这个结束 - user995387
顺便说一句,我想从用户控件中调用它。你能告诉我怎么做吗? - user995387
请发布一个单独的问题以获取翻译。 - Haris Hasan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接