I have a custom WPF TextBox User Control. Im writing some content, but it always detects the same data that was preset on the XAML, new written text is not shown by doing textbox.Text get call.
public partial class SearchBox : UserControl
{
public SearchBox()
{
InitializeComponent();
this.DataContext = this;
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox textBox && textBox.Tag.ToString() == textBox.Text)
textBox.Clear();
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox textBox && string.IsNullOrEmpty(textBox.Text))
textBox.Text = textBox.Tag.ToString();
}
public string Text { get; set; }
public event TextChangedEventHandler TextChanged;
private void TextBox_TextChanged(object sender, TextChangedEventArgs args)
{
TextChangedEventHandler h = TextChanged;
if (h != null)
{
h(this, args);
}
}
}
How it needs to work:
<v:SearchBox x:Name="searchBox" TextChanged="searchBox_TextChanged" Text="Input a keyword to filter..." Tag="Input a keyword to filter..." HorizontalAlignment="Left"/>
User writes on textbox "test" --> textbox.Text returns "Input a keyword to filter..."
Thanks for the help!
Your class inherits from UserControl
and not TextBox
.
Though you haven't shared your XAML for SearchBox
, I assume you have a TextBox
in it, which you are hoping to get the text from. Problem is, the property SearchBox.Text
is different from SearchBox.TextBox.Text
. As a result, even if you change the text in the TextBox
, SearchBox.Text
remains the same.
Solution: use SearchBox.TextBox.Text
for your result.