Processing WPF textbox input events
I have a textbox with default text like "Enter Name"
Once user starts typing some text or focuses on the textbox (with M开发者_如何学GoouseEnter or KeyboardFocus), i want the default text to go and only user input to show.
But if user leaves it blank without any input and then MouseLeave or LostKeyboardFocus, I want the default text to reappear.
I think it is the simplest of pattern I am trying to implement, but not quite getting there.
How can i handle it in elegant standard way ? Do i need to be using custom variables to keep track of state amongst this event flow or WPF textbox events will suffice ?
Pseudo-code Example to do so will be great.
Some pseudo-code here:
textBox.Text = "Please enter text...";
...
private string defaultText = "Please enter text...";
GotFocus()
{
if (textBox.Text == defaultText) textBox.Text = string.Empty;
}
LostFocus()
{
if (textBox.Text == string.Empty) textBox.Text = defaultText;
}
You can set a Style trigger to set the default text on keyboard lost focus like this:
<Window x:Class="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" >
<Window.Resources>
<Style x:Key="textboxStyle" TargetType="{x:Type TextBox}" >
<Style.Triggers>
<Trigger Property="IsKeyboardFocused" Value="False">
<Trigger.Setters>
<Setter Property="Text" Value="Enter text" />
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<TextBox Name="textBoxWithDefaultText" Width="100" Height="30" Style="{StaticResource textboxStyle}" TextChanged="textBoxWithDefaultText_TextChanged"/>
<TextBox Name="textBoxWithoutDefaultText" Width="100" Height="30" />
</StackPanel>
But when you enter Text in TextBox using keyboard that local value takes precedence over style trigger as Text is Dependancy Property. So to make the style trigger work the next time the TextBox text is empty add this code behind:
private void textBoxWithDefaultText_TextChanged(object sender, TextChangedEventArgs e)
{
if(textBoxWithDefaultText.Text == "")
textBoxWithDefaultText.ClearValue(TextBox.TextProperty);
}
精彩评论