创建对话框的实例并从主窗口

时间:2016-04-09 17:58:17

标签: c# c++ wpf qt

我来自Qt,我有一个对话框类,并使用它来从主窗口打开对话框:

void MainWindow::on_pushButton_clicked(){
    Dialog *x = new Dialog();
    x->show();}

现在我想用WPF做同样的事情。 如何创建一个对话框以及如何使用它?

1 个答案:

答案 0 :(得分:0)

定义Window以用作输入对话框:

XAML:

<Window x:Class="WpfApplication1.MyInputDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MyInputDialog"
        Height="130"
        Width="300">
    <DockPanel Margin="15">
        <UniformGrid DockPanel.Dock="Bottom"
                     Margin="5"
                     Rows="1"
                     >
            <Button Content="Ok"
                    x:Name="bOk"
                    IsDefault="True"
                    Click="bOk_Click"
                    HorizontalAlignment="Center"
                    />
            <Button Content="Cancel"
                    x:Name="bCancel"
                    IsCancel="True"
                    Click="bCancel_Click"   
                    HorizontalAlignment="Center"
                    />
        </UniformGrid>        

        <DockPanel Margin="5" >
            <TextBlock DockPanel.Dock="Left"
                        Text="Input a value:"
                        />
            <TextBox x:Name="tbResult"/>

        </DockPanel>
    </DockPanel>
</Window>

代码隐藏:

/// <summary>
/// Interaction logic for MyInputDialog.xaml
/// </summary>
public partial class MyInputDialog : Window
{
    public MyInputDialog()
    {
        InitializeComponent();
    }

    private void bOk_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = true;
    }

    private void bCancel_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
    }
}

然后在主Window展示MyInputDialog模式ShowDialog并检查TextBox

的值
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var dialog = new MyInputDialog();
        if(dialog.ShowDialog()== true)
        {
            var input = dialog.tbResult.Text;
        }
    }