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 }