您可以設置樣式觸發設置這樣的鍵盤失去焦點的默認文本:
<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);
}
太好了。我是WPF和輸入事件的新手。這個簡單的模式有效。還將其應用於鼠標事件。 – 2011-05-28 08:53:09