TextBox, WPF. With TextBoxes, we present a user-editable box for input. And in some cases, a TextBox is an effective way to display program output.
Getting started. It is easy to add a TextBox to a WPF program—please create a C# WPF project. From the Toolbox panel, drag a TextBox control to the designer window.
Attribute example. Now, in the XAML markup, changed the Text attribute to be an empty string. The Text property indicates the string displayed into the TextBox.
Also Add a TextChanged attribute. The Visual Studio editor will offer to insert TextBox_TextChanged after you type "TextChanged" in the XAML.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="10,10,0,0"
TextWrapping="Wrap"
Text=""
VerticalAlignment="Top"
Width="120"
TextChanged="TextBox_TextChanged"/>
</Grid>
</Window>using System.Windows;
using System.Windows.Controls;
namespace WpfApplication2
{
/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
// ... Get control that raised this event.
var textBox = sender as TextBox;
// ... Change Window Title.
this.Title = textBox.Text + "[Length = " + textBox.Text.Length.ToString() + "]";
}
}
}
Text. When accessed, the Text property always returns a string that indicates the characters currently inside the TextBox. It can also be assigned—this changes the current contents.
Info In the example, we access the Text property twice—first to assign it to the Title, and then to get its length.
TextChanged. This event handler is triggered whenever the Text property of the TextBox changes. It is triggered at startup if a default Text attribute is set.
Tip In TextChanged, you can access the source of the event by casting the "sender" object parameter.
Also The TextChangedEventArgs argument contains details of the changes made on the TextBox.
Summary. We discovered how to capture user input into this TextBox (with TextChanged). We finally read the Text property, and assigned the Window Title.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 24, 2024 (simplify).