WPF:创建对话框/提示 [英] WPF: Create a dialog / prompt

查看:55
本文介绍了WPF:创建对话框/提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个对话框/提示,包括用于用户输入的文本框.我的问题是,确认对话框后如何获取文本?通常我会为此创建一个类,将文本保存在属性中.但是我想使用 XAML 设计对话框.所以我必须以某种方式扩展 XAML 代码以将 TextBox 的内容保存在一个属性中 - 但我想这对于纯 XAML 来说是不可能的.实现我想做的事情的最佳方式是什么?如何构建一个可以从 XAML 定义但仍然可以以某种方式返回输入的对话框?感谢您的任何提示!

I need to create a Dialog / Prompt including TextBox for user input. My problem is, how to get the text after having confirmed the dialog? Usually I would make a class for this which would save the text in a property. However I want do design the Dialog using XAML. So I would somehow have to extent the XAML Code to save the content of the TextBox in a property - but I guess that's not possible with pure XAML. What would be the best way to realize what I'd like to do? How to build a dialog which can be defined from XAML but can still somehow return the input? Thanks for any hint!

推荐答案

负责任"的答案是我建议为对话框构建一个 ViewModel 并在 TextBox 上使用双向数据绑定,以便 ViewModel 有一些"ResponseText"属性或什么不是.这很容易做到,但可能有点矫枉过正.

The "responsible" answer would be for me to suggest building a ViewModel for the dialog and use two-way databinding on the TextBox so that the ViewModel had some "ResponseText" property or what not. This is easy enough to do but probably overkill.

务实的答案是只给你的文本框一个 x:Name 以便它成为一个成员并将文本作为一个属性暴露在你的类后面的代码中,如下所示:

The pragmatic answer would be to just give your text box an x:Name so that it becomes a member and expose the text as a property in your code behind class like so:

<!-- Incredibly simplified XAML -->
<Window x:Class="MyDialog">
   <StackPanel>
       <TextBlock Text="Enter some text" />
       <TextBox x:Name="ResponseTextBox" />
       <Button Content="OK" Click="OKButton_Click" />
   </StackPanel>
</Window>

然后在你的代码后面...

Then in your code behind...

partial class MyDialog : Window {

    public MyDialog() {
        InitializeComponent();
    }

    public string ResponseText {
        get { return ResponseTextBox.Text; }
        set { ResponseTextBox.Text = value; }
    }

    private void OKButton_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        DialogResult = true;
    }
}

然后使用它...

var dialog = new MyDialog();
if (dialog.ShowDialog() == true) {
    MessageBox.Show("You said: " + dialog.ResponseText);
}

这篇关于WPF:创建对话框/提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆