当文本框在模板内时如何使文本消失

How to make text disappear when TextBox is within template

我知道如何让文字在书写时消失:我们应该使用 GotFocus LostFocus。 例如,我用这个 TextBox:

<TextBox x:Name="SearchNotes" Foreground="Gray" 
         Text="Search" LostFocus="NoteBox_OnLostFocus"
         GotFocus="NoteBox_GotFocus" BorderThickness="0" 
         Background="WhiteSmoke" TextChanged="TextBox_TextChanged" 
         Width="771"
         />

代码如下:

public void NoteBox_GotFocus(object sender, RoutedEventArgs e)
{
    SearchNotes.Text = "";
    SearchNotes.Foreground = Brushes.White;
}

public void NoteBox_OnLostFocus(object sender, RoutedEventArgs e)
{
    SearchNotes.Text = "Search";
    SearchNotes.Foreground = Brushes.Gray;
}

现在,我正尝试对另一个 TextBox 做同样的事情,但问题是 TextBoxWindow 模板中,所以我没有访问权限从代码到这个 TextBox(或者我不知道如何访问它)

这是XAML代码:

<TextBox x:Name="WindowTextbox" GotFocus="WindowTextbox_GotFocus" LostFocus="WindowTextbox_LostFocus" Text="Type..." TextChanged="WindowTextbox_TextChanged" FontSize="15" Foreground="White" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True" Background="#404040" BorderThickness="0" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Grid.RowSpan="3" Margin="0 0 0 23">
</TextBox>

当我尝试从代码访问它时我不能:

所以我想知道如何处理这个。

这就是 sender 参数的用途,请参阅 Routed Events Overview

The object where the handler was invoked is the object reported by the sender parameter.

private void WindowTextbox_GotFocus(object sender, RoutedEventArgs e)
{
   var textBox = (TextBox)sender;
   textBox.Text = "";
   textBox.Foreground = Brushes.White;
}

private void WindowTextbox_LostFocus(object sender, RoutedEventArgs e)
{
   var textBox = (TextBox)sender;
   textBox.Text = "Search";
   textBox.Foreground = Brushes.Gray;
}