WPF设置TextBox内容为空时的提示文字的两种方式

1.网上普遍的实现形式为下面这一种,供参考。

 1 <TextBox x:Name="TxtUserName1" Grid.Column="1" FontSize="18" TextChanged="TxtUserName1_TextChanged"
 2                              Foreground="#FFB4EEFF" Margin="1" BorderThickness="4" VerticalContentAlignment="Center">
 3                 <TextBox.Resources>
 4                     <VisualBrush x:Key="HintText" TileMode="None" Opacity="0.5" Stretch="None" AlignmentX="Left">
 5                         <VisualBrush.Visual>
 6                             <TextBlock Text="请输入用户名" Foreground="Gray"/>
 7                         </VisualBrush.Visual>
 8                     </VisualBrush>
 9                 </TextBox.Resources>
10                 <TextBox.Style>
11                     <Style TargetType="TextBox">
12                         <Style.Triggers>
13                             <Trigger Property="Text" Value="{x:Null}">
14                                 <Setter Property="Background" Value="{StaticResource HintText}"/>
15                             </Trigger>
16                             <Trigger Property="Text" Value="">
17                                 <Setter Property="Background" Value="{StaticResource HintText}"/>
18                             </Trigger>
19                         </Style.Triggers>
20                     </Style>
21                 </TextBox.Style>
22             </TextBox>

在应用过程中,如果我给TextBox加一个 Background,提示文字就会不正常显示。

2.于是我用了第二个办法实现,在TextBox的位置新增一个TextBlock,TextBlock的内容为提示信息。

在TextBox的TextChanged事件中实现隐藏

Xaml代码:

1 <Grid Grid.Row="3">
2             <TextBox x:Name="TxtUserName2" Grid.Column="1" FontSize="18" TextChanged="TxtUserName2_TextChanged"  Background="AliceBlue"
3                              Foreground="#FFB4EEFF" Margin="1" BorderThickness="4" VerticalContentAlignment="Center">
4             </TextBox>
5             <TextBlock Name="txtTip" Text="请输入用户名" Padding="10"></TextBlock>
6         </Grid>

cs后台代码:

1  private void TxtUserName2_TextChanged(object sender, TextChangedEventArgs e)
2         {
3             txtTip.Visibility = string.IsNullOrEmpty(TxtUserName2.Text) ? Visibility.Visible : Visibility.Hidden;
4         }

 

posted @ 2021-04-09 09:43  十四年新*  阅读(3386)  评论(1编辑  收藏  举报