Eric J.
Eric J.

Reputation: 150198

Prevent WPF TextBox from displaying on multiple lines

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

Upvotes: 4

Views: 6555

Answers (3)

Bathineni
Bathineni

Reputation: 3496

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

Upvotes: 3

Thomas Levesque
Thomas Levesque

Reputation: 292695

Set AcceptsReturn to false, not true. Setting it to true means that it is an acceptable text input.

Upvotes: 2

Rachel
Rachel

Reputation: 132618

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.

Upvotes: 7

Related Questions