I have a WPF TextBox intended to accept a search term and do something with that search term when the user hits the Enter key (with the TextBox focused).
For unexplained reasons, that TextBox allows for multiple lines of text to be entered.
I have set TextWrapping to NoWrap and MaxLines to 1. The associated event handler indicates that it handles the event when Environment.NewLine terminates the text.
Except for the wrapping, everything else is working as expected. How can I prevent the text wrapping?
<TextBox Height="23" Margin="24,1,12,0" Name="txtSearch" VerticalAlignment="Top" TextWrapping="NoWrap" Visibility="Visible" MinWidth="50" LostFocus="txtSearch_LostFocus" AcceptsReturn="True" TextChanged="txtSearch_TextChanged" MaxLines="1" />
private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtSearch.Text.EndsWith(Environment.NewLine))
{
string search = txtSearch.Text.Replace(Environment.NewLine, string.Empty);
e.Handled = true;
MainViewModel vm = (MainViewModel)this.FindResource("viewModel");
vm.SearchText = search;
}
}
Do you mean it Wraps when you hit Enter? Or when the Text gets too long?
You have AcceptsReturn="True", which means the user can use the Enter key inside your TextBox to create a newline. Try setting it to False instead.
Instead of using text changed event you can use previewkeydown or previewkeyup events...
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
e.Handled = true;
// handle search here
}
else
{
// do some thing
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With