问题描述
|
我有一个文本框,其默认文本为\“输入名称\”
一旦用户开始输入一些文本或专注于文本框(使用MouseEnter或KeyboardFocus),我希望使用默认文本,只显示用户输入。
但是,如果用户在没有任何输入的情况下将其留空,然后再选择MouseLeave或LostKeyboardFocus,我希望重新显示默认文本。
我认为这是我尝试实现的最简单的模式,但还不能完全实现。
我如何以优雅的标准方式处理它?我是否需要使用自定义变量来跟踪此事件流中的状态,否则WPF文本框事件就足够了?
这样做的伪代码示例将很棒。
解决方法
一些伪代码在这里:
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;
}
, 您可以设置样式触发器,以设置键盘失去焦点时的默认文本,如下所示:
<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>
但是,当您使用键盘在TextBox中输入Text时,本地值将优先于样式触发器,因为Text是Dependency属性。因此,要使样式触发器在下次TextBox文本为空时起作用,请在后面添加以下代码:
private void textBoxWithDefaultText_TextChanged(object sender,TextChangedEventArgs e)
{
if(textBoxWithDefaultText.Text == \"\")
textBoxWithDefaultText.ClearValue(TextBox.TextProperty);
}