自定义样式例子
代码
<Application.Resources>
<Style x:Key="styledTextBox" TargetType="{x:Type TextBox}">
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Height" Value="28" />
<Setter Property="Foreground" Value="White" />
<Setter Property="CaretBrush" Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border
Background="#0A5D7B"
BorderBrush="#eee"
BorderThickness="0"
CornerRadius="2">
<Grid>
<Border
x:Name="BorderBase"
Background="Transparent"
BorderBrush="Transparent"
BorderThickness="1.4,1.4,1,1" />
<Label
x:Name="TextPrompt"
VerticalAlignment="Center"
Content="{TemplateBinding Tag}"
Focusable="False"
Foreground="Gray"
Visibility="Collapsed" />
<ScrollViewer
x:Name="PART_ContentHost"
Margin="2,0,0,0"
VerticalAlignment="Center" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsFocused" Value="False" />
<Condition Property="Text" Value="" />
</MultiTrigger.Conditions>
<Setter TargetName="TextPrompt" Property="Visibility" Value="Visible" />
</MultiTrigger>
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="BorderBase" Property="BorderThickness" Value="2.4,1.4,1,1" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="Gray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
<TextBox
Width="222"
Height="23"
Style="{StaticResource styledTextBox}"
Text="New TextBox"
TextWrapping="Wrap" />
效果
提示字符串效果
代码
<TextBox
Width="200"
Height="30"
HorizontalAlignment="Center"
VerticalAlignment="Center"
VerticalContentAlignment="Center">
<TextBox.Style>
<Style xmlns:sys="clr-namespace:System;assembly=mscorlib" TargetType="TextBox">
<Style.Resources>
<VisualBrush
x:Key="CueBannerBrush"
AlignmentX="Left"
AlignmentY="Center"
Stretch="None">
<VisualBrush.Visual>
<Label Content="你的提示字符串" Foreground="LightGray" />
</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" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
效果
另一种方式
如果你的工程里引用了MaterialDesignUI库的话,下面的方式更简单:
<TextBox
Name="txtStock"
Grid.Row="0"
Grid.Column="2"
materialDesign:HintAssist.Hint="你的提示字符串"
MaxLength="16"
Text="{Binding StockCode}" />
自动高亮选中功能
代码
<Grid>
<TextBox
Name="MyBox"
Width="200"
Height="23"
GotFocus="UIElement_OnGotFocus"
Text="sample text" />
</Grid>
private void UIElement_OnGotFocus(object sender, RoutedEventArgs e)
{
var textBox = (TextBox)sender;
textBox.Dispatcher.BeginInvoke(new Action(() => textBox.SelectAll()));
}