Enable WPF Textbox Multiline Text

Kailash Chandra Behera | Sunday, July 17, 2022
WPF Textbox
Enable WPF Textbox Multiline Text

Introduction

WPF Textbox has ability to accept multiple line inputs, here this blog “Enable WPF Textbox Multiline Text “, provides code snippets to enable WPF textbox for multiline Text and read text from textbox.

Getting Started

There are two textbox attributes which makes the WPF textbox to to accommodate multiple lines of text. Those are TextWrapping and AcceptsReturn. The TextWrapping attribute allows warp to intered text to a new line when the edge of the textbox control is reached by expanding the height of the textbox control to include room for a new line, if necessary. The AcceptReturn attribute inserts a new line at the current cursor position

To enable WPF Textbox for multiple, you need to set the TextWrapping  valueto Wrap and AcceptReturn value to true. To make the content of the textbox to scroll, you need to set the VerticalScrollBarVisibility value to visible.

XAML code for WPF Textbox Multiline

This following code example shows how to use Extensible Application Markup Language (XAML) to define a TextBox control that will automatically expand to accommodate multiple lines of text.

 <TextBox Name="txtmulitiline" Grid.Row="1" TextWrapping="Wrap" AcceptsReturn="True" BorderBrush="Black" BorderThickness="1" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled"  FontWeight="Bold">  
 </TextBox>  
C# code for WPF Textbox Multiline

This following code example shows how to C# to define a TextBox control that will automatically expand to accommodate multiple lines of text.

 this.txtmulitiline.TextWrapping = TextWrapping.Wrap;  
 this.txtmulitiline.AcceptsReturn = true;  
 this.txtmulitiline.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;  
 this.txtmulitiline.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;  

The following C# code shows how to retrive the line of text from textbox.

 // lineCount may be -1 if TextBox layout info is not up-to-date.  
 int lineCount = txtmulitiline.LineCount;  
 for (int line = 0; line < lineCount; line++)  
 {  
      // GetLineText takes a zero-based line index.  
      MessageBox.Show(txtmulitiline.GetLineText(line));  
 }  

Thanks