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

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

问题描述

我需要创建一个包含TextBox的对话框/提示符以供用户输入。我的问题是,确认对话框后如何获取文本?通常我会为一个类保存一个属性的文本。不过我想用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:名称,使它成为一个成员并公开文本作为您代码中的代码属性,如下所示:

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天全站免登陆