您可以设置样式触发设置这样的键盘失去焦点的默认文本:
<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