Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent WPF TextBox from displaying on multiple lines

Tags:

word-wrap

wpf

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;
    }
}
like image 369
Eric J. Avatar asked Oct 24 '25 01:10

Eric J.


2 Answers

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.

like image 168
Rachel Avatar answered Oct 26 '25 01:10

Rachel


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
    }
}
like image 23
Bathineni Avatar answered Oct 26 '25 01:10

Bathineni