Как использовать OAuth2 со Spring Security в Java
Javaican 14.05.2025
Протокол OAuth2 часто путают с механизмами аутентификации, хотя по сути это протокол авторизации. Представьте, что вместо передачи ключей от всего дома вашему другу, который пришёл полить цветы, вы. . .
Анализ текста на Python с NLTK и Spacy
AI_Generated 14.05.2025
NLTK, старожил в мире обработки естественного языка на Python, содержит богатейшую коллекцию алгоритмов и готовых моделей. Эта библиотека отлично подходит для образовательных целей и. . .
Реализация DI в PHP
Jason-Webb 13.05.2025
Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .
Обработка изображений в реальном времени на C# с OpenCV
stackOverflow 13.05.2025
Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .
POCO, ACE, Loki и другие продвинутые C++ библиотеки
NullReferenced 13.05.2025
В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .
Паттерны проектирования GoF на C#
UnmanagedCoder 13.05.2025
Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .
Создаем CLI приложение на Python с Prompt Toolkit
py-thonny 13.05.2025
Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .
Конвейеры ETL с Apache Airflow и Python
AI_Generated 13.05.2025
ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .
Выполнение асинхронных задач в Python с asyncio
py-thonny 12.05.2025
Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .
Работа с gRPC сервисами на C#
UnmanagedCoder 12.05.2025
gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .
Represents a control that can be used to display single-format, multi-line
text.
Inheritance
System.Object
TextBox
Inherited Members
System.Object.Equals(System.Object)
System.Object.Equals(System.Object, System.Object)
System.Object.GetHashCode()
System.Object.GetType()
System.Object.MemberwiseClone()
System.Object.ReferenceEquals(System.Object, System.Object)
System.Object.ToString()
Namespace: System.Windows.Controls
Assembly: OpenSilver.dll
Syntax
[TemplatePart(Name = "ContentElement", Type = typeof(FrameworkElement))]
public class TextBox : Control, IControl, IFrameworkElement, IUIElement, IDependencyObject
Examples
TextBoxName.Text = "Some text";
Constructors
|
Improve this Doc
View Source
TextBox()
Declaration
Fields
|
Improve this Doc
View Source
AcceptsReturnProperty
Identifies the AcceptsReturn dependency property.
Declaration
public static readonly DependencyProperty AcceptsReturnProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
AcceptsTabProperty
Identifies the AcceptsReturn dependency property.
Declaration
public static readonly DependencyProperty AcceptsTabProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
CaretBrushProperty
Identify the CaretBrush dependency property
Declaration
public static readonly DependencyProperty CaretBrushProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
HorizontalScrollBarVisibilityProperty
Identifies the HorizontalScrollBarVisibility dependency property.
Declaration
public static readonly DependencyProperty HorizontalScrollBarVisibilityProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
IsReadOnlyProperty
Declaration
public static readonly DependencyProperty IsReadOnlyProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
IsSpellCheckEnabledProperty
Declaration
public static readonly DependencyProperty IsSpellCheckEnabledProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
LineHeightProperty
Identifies the LineHeight dependency property.
Declaration
public static readonly DependencyProperty LineHeightProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
MaxLengthProperty
Identifies the MaxLength dependency property.
Declaration
public static readonly DependencyProperty MaxLengthProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
PlaceholderTextProperty
Identifies the PlaceholderText dependency property.
Declaration
public static readonly DependencyProperty PlaceholderTextProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
SelectionBackgroundProperty
Declaration
[NotImplemented]
public static readonly DependencyProperty SelectionBackgroundProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
SelectionForegroundProperty
Declaration
[NotImplemented]
public static readonly DependencyProperty SelectionForegroundProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
TextAlignmentProperty
Declaration
public static readonly DependencyProperty TextAlignmentProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
TextDecorationsProperty
Identifies the TextDecorations dependency property.
Declaration
public static readonly DependencyProperty TextDecorationsProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
TextProperty
Identifies the Text dependency property.
Declaration
public static readonly DependencyProperty TextProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
TextWrappingProperty
Declaration
public static readonly DependencyProperty TextWrappingProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
|
Improve this Doc
View Source
VerticalScrollBarVisibilityProperty
Identifies the VerticalScrollBarVisibility dependency property.
Declaration
public static readonly DependencyProperty VerticalScrollBarVisibilityProperty
Field Value
Type | Description |
---|---|
DependencyProperty |
Properties
|
Improve this Doc
View Source
AcceptsReturn
Gets or sets the value that determines whether the text box allows and displays
the newline or return characters.
Declaration
public bool AcceptsReturn { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean |
|
Improve this Doc
View Source
AcceptsTab
Gets or sets the value that determines whether pressing tab while the TextBox has the focus will add a tabulation in the text or set the focus to the next element.
True to add a tabulation, false to set the focus to the next element.
Declaration
public bool AcceptsTab { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean |
|
Improve this Doc
View Source
BaselineOffset
Gets a value by which each line of text is offset from a baseline.
Declaration
public double BaselineOffset { get; }
Property Value
Type | Description |
---|---|
System.Double |
The amount by which each line of text is offset from the baseline, in device |
|
Improve this Doc
View Source
CaretBrush
Gets or sets the brush that is used to render the vertical bar that indicates the
insertion point.
Declaration
public Brush CaretBrush { get; set; }
Property Value
Type | Description |
---|---|
Brush |
A brush that is used to render the vertical bar that indicates the insertion point. |
|
Improve this Doc
View Source
HorizontalScrollBarVisibility
Gets or sets a value that indicates whether a horizontal ScrollBar should
be displayed.
Returns a ScrollBarVisibility value that indicates whether a horizontal ScrollBar
should be displayed. The default value is Hidden.
Declaration
public ScrollBarVisibility HorizontalScrollBarVisibility { get; set; }
Property Value
Type | Description |
---|---|
ScrollBarVisibility |
|
Improve this Doc
View Source
IsReadOnly
Declaration
public bool IsReadOnly { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean |
|
Improve this Doc
View Source
IsSpellCheckEnabled
Gets or sets a value that specifies whether the TextBox input
interacts with a spell check engine.
Declaration
public bool IsSpellCheckEnabled { get; set; }
Property Value
Type | Description |
---|---|
System.Boolean |
true if the TextBox input interacts with a spell check engine; |
|
Improve this Doc
View Source
LineHeight
Gets or sets the height of each line of content.
Declaration
public double LineHeight { get; set; }
Property Value
Type | Description |
---|---|
System.Double |
The height of each line in pixels. A value of 0 indicates that |
Exceptions
Type | Condition |
---|---|
System.ArgumentException |
LineHeight is set to a non-positive value. |
|
Improve this Doc
View Source
MaxLength
Gets or sets the value that determines the maximum number of characters allowed
for user input.
Declaration
public int MaxLength { get; set; }
Property Value
Type | Description |
---|---|
System.Int32 |
|
Improve this Doc
View Source
PlaceholderText
Gets or sets the text that is displayed in the control until the value is changed by a user action or some other operation.
Declaration
public string PlaceholderText { get; set; }
Property Value
Type | Description |
---|---|
System.String |
|
Improve this Doc
View Source
SelectedText
Declaration
public string SelectedText { get; set; }
Property Value
Type | Description |
---|---|
System.String |
|
Improve this Doc
View Source
SelectionBackground
Declaration
[NotImplemented]
public Brush SelectionBackground { get; set; }
Property Value
Type | Description |
---|---|
Brush |
|
Improve this Doc
View Source
SelectionForeground
Declaration
[NotImplemented]
public Brush SelectionForeground { get; set; }
Property Value
Type | Description |
---|---|
Brush |
|
Improve this Doc
View Source
SelectionLength
Declaration
public int SelectionLength { get; set; }
Property Value
Type | Description |
---|---|
System.Int32 |
|
Improve this Doc
View Source
SelectionStart
Declaration
public int SelectionStart { get; set; }
Property Value
Type | Description |
---|---|
System.Int32 |
|
Improve this Doc
View Source
Text
Gets or sets the text displayed in the TextBox.
Declaration
public string Text { get; set; }
Property Value
Type | Description |
---|---|
System.String |
|
Improve this Doc
View Source
TextAlignment
Gets or sets how the text should be aligned in the text box.
Declaration
public TextAlignment TextAlignment { get; set; }
Property Value
Type | Description |
---|---|
TextAlignment |
One of the TextAlignment enumeration values. |
|
Improve this Doc
View Source
TextDecorations
Gets or sets the text decorations (underline, strikethrough…).
Declaration
public TextDecorationCollection TextDecorations { get; set; }
Property Value
Type | Description |
---|---|
TextDecorationCollection |
|
Improve this Doc
View Source
TextWrapping
Gets or sets how line breaking occurs if a line of text extends beyond the available width of
the text box.
Declaration
public TextWrapping TextWrapping { get; set; }
Property Value
Type | Description |
---|---|
TextWrapping |
One of the TextWrapping values. The default is NoWrap. |
|
Improve this Doc
View Source
VerticalScrollBarVisibility
Gets or sets a value that indicates whether a vertical ScrollBar should be displayed.
Declaration
public ScrollBarVisibility VerticalScrollBarVisibility { get; set; }
Property Value
Type | Description |
---|---|
ScrollBarVisibility |
Methods
|
Improve this Doc
View Source
OnApplyTemplate()
Builds the visual tree for the
TextBox control when a new
template is applied.
Declaration
public override void OnApplyTemplate()
Overrides
|
Improve this Doc
View Source
OnCreateAutomationPeer()
Returns a TextBoxAutomationPeer for use by the Silverlight automation
infrastructure.
Declaration
protected override AutomationPeer OnCreateAutomationPeer()
Returns
Type | Description |
---|---|
AutomationPeer |
A TextBoxAutomationPeer for the TextBox object. |
Overrides
|
Improve this Doc
View Source
OnGotFocus(RoutedEventArgs)
Declaration
protected override void OnGotFocus(RoutedEventArgs e)
Parameters
Type | Name | Description |
---|---|---|
RoutedEventArgs | e |
Overrides
|
Improve this Doc
View Source
OnKeyDown(KeyEventArgs)
Declaration
protected override void OnKeyDown(KeyEventArgs e)
Parameters
Type | Name | Description |
---|---|---|
KeyEventArgs | e |
Overrides
|
Improve this Doc
View Source
OnLostFocus(RoutedEventArgs)
Declaration
protected override void OnLostFocus(RoutedEventArgs e)
Parameters
Type | Name | Description |
---|---|---|
RoutedEventArgs | e |
Overrides
|
Improve this Doc
View Source
OnMouseEnter(MouseEventArgs)
Declaration
protected override void OnMouseEnter(MouseEventArgs e)
Parameters
Type | Name | Description |
---|---|---|
MouseEventArgs | e |
Overrides
|
Improve this Doc
View Source
OnMouseLeave(MouseEventArgs)
Declaration
protected override void OnMouseLeave(MouseEventArgs e)
Parameters
Type | Name | Description |
---|---|---|
MouseEventArgs | e |
Overrides
|
Improve this Doc
View Source
OnMouseLeftButtonDown(MouseButtonEventArgs)
Declaration
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
Parameters
Type | Name | Description |
---|---|---|
MouseButtonEventArgs | e |
Overrides
|
Improve this Doc
View Source
OnMouseLeftButtonUp(MouseButtonEventArgs)
Declaration
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
Parameters
Type | Name | Description |
---|---|---|
MouseButtonEventArgs | e |
Overrides
|
Improve this Doc
View Source
OnTextChanged(TextChangedEventArgs)
Raises the TextChanged event
Declaration
protected virtual void OnTextChanged(TextChangedEventArgs eventArgs)
Parameters
Type | Name | Description |
---|---|---|
TextChangedEventArgs | eventArgs |
The arguments for the event. |
|
Improve this Doc
View Source
OnTextInput(TextCompositionEventArgs)
Declaration
protected override void OnTextInput(TextCompositionEventArgs e)
Parameters
Type | Name | Description |
---|---|---|
TextCompositionEventArgs | e |
Overrides
|
Improve this Doc
View Source
Select(Int32, Int32)
Declaration
public void Select(int start, int length)
Parameters
Type | Name | Description |
---|---|---|
System.Int32 | start | |
System.Int32 | length |
|
Improve this Doc
View Source
SelectAll()
Selects all text in the text box.
Declaration
Events
|
Improve this Doc
View Source
SelectionChanged
Declaration
[NotImplemented]
public event RoutedEventHandler SelectionChanged
Event Type
Type | Description |
---|---|
RoutedEventHandler |
|
Improve this Doc
View Source
TextChanged
Occurs when the text is changed.
Declaration
public event TextChangedEventHandler TextChanged
Event Type
Type | Description |
---|---|
TextChangedEventHandler |
Extension Methods
Represents a control that can be used to display or edit plain text.
1 |
public class TextBox : System.Windows.Controls.TextBox, IDataInput |
Create TextBox
1 |
<hc:TextBox /> |
1 |
var textBox = new TextBox(); |
Enter text
This example shows how to use the Text property to set the initial text content of a TextBox control:
1 |
<hc:TextBox Text="This is the content"/> |
1 |
textBox.Text = "This is the content"; |
The generated TextBox is shown below:
For more examples of TextBox, you can refer to the Document of its base class.
Set title and placeholder text
You can add a Header and a Placeholder to a TextBox to indicate to the user its purpose. To use these two attributes
1 |
<hc:TextBox hc:InfoElement.Placeholder="Please enter the content" |
Styles
Style |
---|
TextBoxPlusBaseStyle |
TextBoxPlus.Small |
Attributes
Property | Description |
---|---|
Text | Gets or sets the text content of the textbox. |
TextType
TextType | TextType | TextType |
---|---|---|
NDouble | Number | |
Chinese | NInt | PDouble |
Common | NnDouble | PInt |
Digits | NnInt | Phone |
Double | NpDouble | Url |
Int | NpInt | |
Persian Only Custom Version |
IranNationalCode Only Custom Version |
you can use regex pattern in texttype
if you want to use RegexPatter, you should Set TextType
to Anything except Common
1 |
Using HandyControl.Tools; |
1 |
<hc:TextBox TextType="Mail" hc:InfoElement.RegexPattern="^[0-9]*(?:\.[0-9]+)?$"/> |
Validation
for validation follow instructions:
bind to ValidationRule
1 |
<hc:TextBox hc:InfoElement.Placeholder="Please Enter Email" hc:InfoElement.Title="Title" hc:InfoElement.Necessary="True" Margin="0,16,0,0"> |
Last Updated :
25 Mar, 2025
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or multiple lines. The TextBox is a class and it is defined under System.Windows.Forms namespace.
Ways to Create a TextBox In Windows Forms
There are mainly two ways to create a TextBox in Windows forms which are mentioned below.
- Drag and drop (Design-Time)
- Custom TextBox (Run-Time)
Drag and drop (Design-Time)
This is the easiest way to create a TextBox in Windows Forms using Visual Studio we just have to open the toolbox and drag and drop the text box on the form in the designer and further we can change the appearance of the TextBox using the properties. Follow these steps to create a TextBox.
Step 1: Now locate the project with the name here we are using the default name which is Form1 and it will open a form in the editor that we can further modify.
In the image, we have two files that are open one Design and there is Form1.cs these two play a major role. We use the Form 1.cs file for the custom logic.
Step 2: Now open a Toolbox go to the view > Toolbox or ctrl + alt + x.
Step 3. Now open the common controls and drag and drop the TextBox on the form where we want to it be placed.
Step 4. Now open the properties of the TextBox press right-click on the TextBox and it will open the properties solution explorer now we can change the button appearance of the textbox and also add different properties like default text.
Output:
Custom TextBox (Run Time)
In this method, we are going to modify the Form1.cs file and add custom code modification in C# with the help of the TextBox class. The following steps show how to create a TextBox dynamically:
Step 1: Create a textbox using the TextBox() constructor provided by the TextBox class.
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2: After creating TextBox, set the properties of the TextBox provided by the TextBox class.
// Set location of the textbox
Mytextbox.Location = new Point(187, 51);
// Set background color of the textbox
Mytextbox.BackColor = Color.LightGray;
// Set the foreground color of the textbox
Mytextbox.ForeColor = Color.DarkOliveGreen;
// Set the size of the textbox
Mytextbox.AutoSize = true;
// Set the name of the textbox
Mytextbox.Name = “text_box1”;
Step 3: And last add this textbox control to form using Add() method.
// Add this textbox to form
this.Controls.Add(Mytextbox);
Step 4: Now double-click on the form in Design and it will open the Form1.cs file where code is written in C#. Here the program file is Form 1.cs Now write this code in Form1.cs file
Form1.cs file:
C#
namespace WinFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Label Label myLabel = new Label(); myLabel.Location = new Point(96, 54); myLabel.Text = "Enter Your Name"; myLabel.AutoSize = true; myLabel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(myLabel); // Creating and setting the properties of TextBox TextBox myTextBox = new TextBox(); myTextBox.Location = new Point(187, 51); myTextBox.BackColor = Color.LightGray; myTextBox.ForeColor = Color.DarkOliveGreen; myTextBox.AutoSize = true; myTextBox.Name = "textBox1"; // Add this textbox to form this.Controls.Add(myTextBox); } } }
Output:
Properties
Property | Description |
---|---|
Text | This property is used to set the text inside the TextBox. |
TextAlign | It is used to Set or get the alignment of the text inside the TextBox for example left, centre, and right. |
MaxLength | Used to set or get the maximum number of characters the user can type into the TextBox. |
Multiline | This is used to set or determine whether the TextBox allows multiple lines of text. If press enter it allows you to write in the next line. |
PasswordChar | It is used to set or get the character used to hide text used where showing the password characters. |
ReadOnly | This property is used to set or get whether the TextBox is read-only (users can’t edit the text). |
WordWrap | Sets or gets whether the text automatically moves to the next line when it’s too long for the box (only for multiline). |
ScrollBars | Sets or gets which type of scroll bars (horizontal, vertical, both, or none) appear in the TextBox. |
Dock | Sets or gets how the TextBox is positioned in its container (e.g., fill, top, left). |
Anchor | Sets or gets which edges of the parent container the TextBox should stay anchored to when resized. |
BorderStyle | Sets or gets the style of the border around the TextBox (e.g., solid line, 3D, no border). |
Enabled | Sets or gets whether the TextBox is enabled (if false , users can’t interact with it). |
Focused | This is the commonly used property to check if the TextBox currently has focus if it is selected. |
Font | Sets or gets the font used for the text (like size and style). |
ForeColor | Sets or gets the colour of the text inside the TextBox. |
BackColor | Sets or gets the background colour of the TextBox. |
AcceptsReturn | Sets whether pressing the Enter key adds a new line (used for multi-line TextBox). |
HideSelection | Sets whether selected text is hidden when the TextBox loses focus. |
SelectionStart | It is used to set from where the selected text starts in the TextBox. |
SelectionLength | This property gets or sets the length of the selected text. |
ShortcutsEnabled | It sets the keyboard shortcuts such as copy (Ctrl + C) or paste (Ctrl + P). |
Clear() | This property is used to clear the text inside the TextBox. |
SelectAll() | We can use this property to select all the text inside the TextBox. |
Основные элементы управления:
Этот элемент управления является базовым, среди полей ввода в WPF, и позволяет конечному пользователю вводить текст, как простой однострочный (диалоговое окно), так и многострочный (редактор).
Однострочный TextBox
TextBox является крайне часто используемым элементом, и Вам даже нет необходимости использовать множество свойств для того, чтобы получить полномасштабное текстовое поле для ввода. Вот пример скелета такого элемента:
<Window x:Class="WpfTutorialSamples.Basic_controls.TextBoxSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TextBoxSample" Height="80" Width="250">
<StackPanel Margin="10">
<TextBox />
</StackPanel>
</Window>
Это все, что Вам необходимо для получения текстового поля ввода. Я добавил в него текст после запуска примера и сделал скриншот. Но Вы также можете сделать это в коде, предварительно заполнив поле, используя свойство Text:
<TextBox Text="Hello, world!" />
Попробуйте кликнуть правой кнопкой мыши на TextBox. Вы увидите меню с опциями, позволяющими Вам использовать TextBox с буфером обмена Windows. Горячие клавиши отмены и повтора (Ctrl+Z и Ctrl+Y) будут работать по умолчанию, и этот функционал Вы получаете сразу же, «from box»!
Многострочный TextBox
Запустив предыдущий пример, Вы заметите, что TextBox по умолчанию является однострочным элементом. Ничего не произойдет при нажатии на Enter, и если Вы введете больше текста, чем позволяет одна строка, ввод просто прекратится. Однако, достаточно просто сделать из TextBox многострочный редактор:
<Window x:Class="WpfTutorialSamples.Basic_controls.TextBoxSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TextBoxSample" Height="160" Width="280">
<Grid Margin="10">
<TextBox AcceptsReturn="True" TextWrapping="Wrap" />
</Grid>
</Window>
Здесь я добавил два свойства: AcceptsReturn превращает TextBox в многострочный элемент, позволяя использовать клавишу Enter/Return для перехода на следующую строку, а свойство TextWrapping реализует автоматический перенос строки на новую, при достижении конца строки.
Проверка орфографии в TextBox
Дополнительным бонусом TextBox является то, что он поддерживает автоматическую проверку орфограции английского и некоторых других языков (французский, немецкий и испанский).
Этот механизм похож на проверку в Microsoft Word, где ошибки написания подчеркиваются, и, по нажатию правой кнопкой мыши, Вам предлагаются варианты исправления. Включить эту проверку в TextBox очень легко:
<Window x:Class="WpfTutorialSamples.Basic_controls.TextBoxSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TextBoxSample" Height="160" Width="280">
<Grid Margin="10">
<TextBox AcceptsReturn="True" TextWrapping="Wrap" SpellCheck.IsEnabled="True" Language="en-US" />
</Grid>
</Window>
В качестве основы мы использовали предыдущий пример многострочного TextBox, при этом я добавил два новых свойства: SpellCheck.IsEnabled, которое включает проверку орфографии элемента и Language — информирующий приложение о том, какой язык используется по умолчанию.
TextBox и работа с выделенными словами
Как и любой другой элемент управления Windows, TextBox позволяет выделять текст: например для удаления слова или вставки текста из буфера обмена. TextBox в WPF имеет несколько свойств для работы с выделенным текстом, которые Вы можете либо пронаблюдать, либо изменить. В следующем примере мы проанализируем следующие свойства:
<Window x:Class="WpfTutorialSamples.Basic_controls.TextBoxSelectionSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TextBoxSelectionSample" Height="150" Width="300">
<DockPanel Margin="10">
<TextBox SelectionChanged="TextBox_SelectionChanged" DockPanel.Dock="Top" />
<TextBox Name="txtStatus" AcceptsReturn="True" TextWrapping="Wrap" IsReadOnly="True" />
</DockPanel>
</Window>
Пример состоит из двух элементов TextBox: один для редактирования, а второй для отображения статуса выбранного текста. Для последнего мы установили свойство IsReadOnly как true, во избежание редактирования текста, предназначенного для отображения статусов. Мы подписываем первый TextBox на событие SelectionChanged, которое обрабатываем в CodeBehind следующим образом:
using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace WpfTutorialSamples.Basic_controls
{
public partial class TextBoxSelectionSample : Window
{
public TextBoxSelectionSample()
{
InitializeComponent();
}
private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
TextBox textBox = sender as TextBox;
txtStatus.Text = "Selection starts at character #" + textBox.SelectionStart + Environment.NewLine;
txtStatus.Text += "Selection is " + textBox.SelectionLength + " character(s) long" + Environment.NewLine;
txtStatus.Text += "Selected text: '" + textBox.SelectedText + "'";
}
}
}
Для достижения результата мы использовали здесь три интересных свойства:
SelectionStart, которое дает нам текущее положение курсора либо, в случае выделенного текста — место, где этот текст начинается.
SelectionLength дает нам длину текущего выделенного текста, если он существует. В противном случае свойство вернет нам 0.
SelectedText возвращает текущую выделенную строку либо пустую строку при отсутствии выделенного текста.
Модифицирование выделенного текста
Все эти свойства являются свойствами чтения и записи, это значит, что Вы можете их также и модифицировать. Например, Вы можете установить свойства SelectionStart и SelectionLength на выбор текста определенной длины или свойство SelectedText для вставки строки. Просто помните, что для реализации подобных механизмов, TextBox должен находится в фокусе. Иными словами чтобы это работало, сначала используйте метод Focus().
This article has been fully translated into the following languages:
-
Catalan
-
Chinese
-
Czech
-
Danish
-
Dutch
-
French
-
German
-
Hindi
-
Hungarian
-
Italian
-
Japanese
-
Korean
-
Polish
-
Portuguese
-
Romanian
-
Russian
-
Slovak
-
Spanish
-
Turkish
-
Ukrainian
-
Vietnamese
Is your preferred language not on the list? Click here to help us translate this article into your language!