1. XAML 代码
<TextBox Width="250" x:Name="UserNameBox" Text="{Binding UserName}" Grid.Row="1" Grid.Column="2" HorizontalAlignment="Right">
<TextBox.Style>
<Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="{StaticResource LoginEmailHint}" Foreground="Gray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter Property="Background" Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" Width="Auto" Height="Auto" BorderThickness="1" BorderBrush="#FF7F9DB9">
<Grid x:Name="grid" Background="#FFFFFF">
<ScrollViewer VerticalAlignment="Center" HorizontalAlignment="Left"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
2. 在code behind 控制它失去焦点且值不为null 或者 empty的style
<Style x:Key="CenterTextStyle" TargetType="{x:Type TextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" Width="Auto" Height="Auto" BorderThickness="1" BorderBrush="#FF7F9DB9">
<Grid x:Name="grid" Background="#FFFFFF">
<ScrollViewer x:Name="PART_ContentHost" VerticalAlignment="Center" HorizontalAlignment="Left"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Code behind:
this.UserNameBox.LostFocus += UserNameBox_LostFocus;
private void UserNameBox_LostFocus(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(this.UserNameBox.Text))
{
this.UserNameBox.Style = (Style)Application.Current.Resources["CenterTextStyle"];
}
}