当您启动应用程序时,将出现一个带有文字“hello”的文本框。
我的问题是:
当您点击文本框以输入数据时,我想在XAML代码中自动删除文本,该怎么做?
处理UIElement.GotFocus
事件,在处理程序中清除文本。您还需要删除处理程序,以便如果第二次单击TextBox
,不会丢失已经输入的内容。
可以参考以下代码:
XAML:
<TextBox Text="Hello" GotFocus="TextBox_GotFocus" />
代码后置文件:
public void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = (TextBox)sender;
tb.Text = string.Empty;
tb.GotFocus -= TextBox_GotFocus;
}
<Grid>
<TextBox Text="This is the prompt text"
FontStyle="Italic"
Foreground="LightGray"
Focusable="False">
</TextBox>
<TextBox Text="{Binding TextProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Focusable="True">
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="Opacity"
Value="1" />
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsFocused"
Value="False" />
<Condition Property="Text"
Value="" />
</MultiTrigger.Conditions>
<Setter Property="Opacity"
Value="0" />
</MultiTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Grid>
您需要实现GetFocus和LostFocus两个事件。这样,如果没有输入文本,您可以在失去焦点事件中将默认文本设置回来。
private const string defaultText = "Hello";
private void myTextBox_GotFocus(object sender, RoutedEventArgs e)
{
myTextBox.Text = myTextBox.Text == defaultText ? string.Empty : myTextBox.Text;
}
private void myTextBox_LostFocus(object sender, RoutedEventArgs e)
{
myTextBox.Text = myTextBox.Text == string.Empty ? defaultText : myTextBox.Text;
}
<TextBox Text="Search..."
Width="250"
Foreground="LightGray"
GotFocus="TextBox_GotFocus"
LostFocus="TextBox_LostFocus" />
C#
void TextBox_GotFocus( object sender, RoutedEventArgs e )
{
TextBox box = sender as TextBox;
box.Text = string.Empty;
box.Foreground = Brushes.Black;
box.GotFocus -= TextBox_GotFocus;
}
void TextBox.LostFocus( object sender, RoutedEventArgs e )
{
TextBox box = sender as TextBox;
if( box.Text.Trim().Equals( string.Empty ) )
{
box.Text = "Search...";
box.Foreground = Brushes.LightGray;
box.GotFocus += TextBox_GotFocus;
}
}
public void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = (TextBox)sender;
if(tb.Text != "SOME DEFAULT TEXT")
{
String persentContentWithDefaultString = t.Text as string;
tb.Text = persentContentWithDefaultString[0].ToString();
// set cursor position
tb.Select(1, 0);
tb.GotFocus -= TextBox_GotFocus;
}
}
实际上,在我的页面上,有两个文本框和一个按钮。[用户名、密码和点击按钮]。默认情况下,焦点会移到我的第一个文本框上,用户无法看到默认文本。
<TextBox Name="Filename"
Grid.Column="0"
Height="23"
Margin="10,9,0,0"
Text="Enter Export Filename here"
Width="193"
GotFocus="Filename_GotFocus"
/>
代码后台:
private void Filename_GotFocus(object sender, RoutedEventArgs e)
{
Filename.Text = "";
}
你也可以使用 Tap 方法,它同样有效。
private void tb1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
tb1.Text = "";
}
private void Filename_GotFocus(object sender, RoutedEventArgs e)
{
Filename.Text = "";
}
或者我喜欢这个选项
private void Filename_GotFocus(object sender, RoutedEventArgs e)
{
Filename.clear();
}
这个问题的要求只是清空文本框。