Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Create a dialog / prompt

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!

like image 688
stefan.at.wpf Avatar asked May 09 '10 03:05

stefan.at.wpf


People also ask

What is dialog in WPF?

Common dialog boxes As a user uses a common dialog box in one application, they don't need to learn how to use that dialog box in other applications. WPF encapsulates the open file, save file, and print common dialog boxes and exposes them as managed classes for you to use in standalone applications.

What is a StackPanel WPF?

A StackPanel allows you to stack elements in a specified direction. By using properties that are defined on StackPanel, content can flow both vertically, which is the default setting, or horizontally.

What is a dialog box?

A dialog box is a temporary window an application creates to retrieve user input. An application typically uses dialog boxes to prompt the user for additional information for menu items.


1 Answers

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.

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;     } } 

Then to use it...

var dialog = new MyDialog(); if (dialog.ShowDialog() == true) {     MessageBox.Show("You said: " + dialog.ResponseText); } 
like image 155
Josh Avatar answered Sep 29 '22 10:09

Josh