C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The Text property indicates the string displayed (or typed by the user) into the TextBox.
Example markup: 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>
Example code: C#
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() + "]";
}
}
}
Info: In the example, we access the Text property twice—first to assign it to the Title, and then to get its length.
PropertyString LengthTip: In TextChanged, you can access the source of the event by casting the "sender" object parameter.
AsObjectAlso: The TextChangedEventArgs argument contains details of the changes made on the TextBox.
AcceptsTab: Normally the TextBox does not accept tabs. Instead, focus changes to the next control. AcceptsTab changes this behavior.
Tip: In my experience, these two "accepts" properties are important in many programs. They expand the domain of uses for this control.
Screenshot: The image shows a TextBox, from a real program, that has padding of 4. This is inner padding.
And: Padding helps when the TextBox is right on the window edge. A margin can sometimes alleviate the need for this much Padding.