2011-05-28 34 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); 
    }