如何使用WPF窗口作为消息框?

use*_*387 4 .net c# wpf

我创建了一个带有一些风格的小窗口.现在我想像MessageBox一样使用它.我怎样才能实现它?

编辑:我是WPF的新手.我试着像这样在主窗口中调用它.

Window1 messageBox = new Window1();
messageBox.Show();
messageBox.Activate();
Run Code Online (Sandbox Code Playgroud)

问题是新生成的窗口在主窗口后面消失,而不让我点击其中的操作按钮.

Har*_*san 7

使用ShowDialog而不是Show方法来弹出消息框窗口.通过这种方式,用户将首先关闭弹出窗口或消息框窗口,然后再返回主窗口

 MessageWindow message= new MessageWindow();
 message.ShowDialog();
Run Code Online (Sandbox Code Playgroud)

编辑

您显然希望在主窗口中找到结果吗?你可以用几种方式做到这一点.最简单的方法是在MainWindow中公开一个公共方法

public GetResult(bool result)
{
   //your logic
} 
Run Code Online (Sandbox Code Playgroud)

创建MessageWindow的构造函数,将MainWindow作为参数

 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();
Run Code Online (Sandbox Code Playgroud)