Home > Back-end >  How to make text disappear when TextBox is within template
How to make text disappear when TextBox is within template

Time:02-23

I knew how to make text disappear while writing: we should use GotFocus LostFocus. For the example I did it with this TextBox:

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

Here is the code:

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;
}

Now, I am trying to do the same thing with another TextBox, but the problem is that the TextBoxis within a Window template so I don't have access to this TextBox from code (or I don't know how to access it)

This is XAML code:

<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>

When I am trying to access this from code I can't:

Error, the WindowTextBox is not found.

So I wanna know how to deal with this.

CodePudding user response:

That is what the sender parameter is for, see 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;
}

CodePudding user response:

Do you need the watermark of the textbox?
https://docs.microsoft.com/en-us/dotnet/desktop/wpf/controls/how-to-add-a-watermark-to-a-textbox?view=netframeworkdesktop-4.8
or
Create WPF Watermark in Pure XAML

  • Related