2011-05-28 93 views
1

我有一个默认文本的文本框一样。一旦用户开始输入一些文字或侧重于文本框(用的MouseEnter或KeyboardFocus)“输入名称”处理WPF文本框中输入事件

,我想默认的文本去只有用户输入才能显示。

但是,如果用户在没有任何输入的情况下将其留空,然后使用MouseLeave或LostKeyboardFocus,我希望默认文本重新出现。

我认为这是我试图实现的最简单的模式,但并不完全实现。

如何以优雅的标准方式处理它?我是否需要使用自定义变量来跟踪这个事件流中的状态或者WPF文本框事件就足够了?

伪代码这样做的例子会很好。

回答

0

一些伪代码在这里:

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; 
} 
+0

太好了。我是WPF和输入事件的新手。这个简单的模式有效。还将其应用于鼠标事件。 – 2011-05-28 08:53:09

0

您可以设置样式触发设置这样的键盘失去焦点的默认文本:

<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文本为空时添加此代码:

private void textBoxWithDefaultText_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     if(textBoxWithDefaultText.Text == "") 
      textBoxWithDefaultText.ClearValue(TextBox.TextProperty); 
    }