public class TextBoxExtHelper { public static string GetIsNullString(DependencyObject obj) { return (string)obj.GetValue(IsNullStringProperty); } public static void SetIsNullString(DependencyObject obj, string value) { obj.SetValue(IsNullStringProperty, value); } // Using a DependencyProperty as the backing store for IsNullString. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsNullStringProperty = DependencyProperty.RegisterAttached("IsNullString", typeof(string), typeof(TextBoxExtHelper), new PropertyMetadata("")); }
添加个附加属性,文本为空时,显示的水印名称
<Style x:Key="TextBoxStyleWithWatermark" TargetType="{x:Type TextBox}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Border x:Name="Bg" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <Grid x:Name="PART_InnerGrid"> <!--文本和水印--> <ScrollViewer x:Name="PART_ContentHost" BorderThickness="0" Grid.Column="1" IsTabStop="False" Margin="2" VerticalAlignment="Stretch" Background="{x:Null}" /> <TextBlock x:Name="WaterMark" Grid.Column="1" VerticalAlignment="Center" Foreground="Silver" FontSize="18" Text="{TemplateBinding txtExt:TextBoxExtHelper.IsNullString}" Visibility="Collapsed" Padding="5,0,0,0" /> </Grid> </Border> <ControlTemplate.Triggers> <!--当Text为空时,隐藏删除按钮--> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},Path=Text}" Value=""> <Setter Property="Visibility" TargetName="WaterMark" Value="Visible" /> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
添加textbox的style
用法如下:
<TextBox x:Name="txt" Style="{StaticResource TextBoxStyleWithWatermark}" Width="120" Height="23" txtExt:TextBoxExtHelper.IsNullString="请输入文本"/>