Как подписать textbox c

от admin

Как подписать textbox c

Для ввода и редактирования текста предназначены текстовые поля — элемент TextBox. Так же как и у элемента Label текст элемента TextBox можно установить или получить с помощью свойства Text.

По умолчанию при переносе элемента с панели инструментов создается однострочное текстовое поле. Для отображения больших объемов информации в текстовом поле нужно использовать его свойства Multiline и ScrollBars . При установке для свойства Multiline значения true, все избыточные символы, которые выходят за границы поля, будут переноситься на новую строку.

Кроме того, можно сделать прокрутку текстового поля, установив для его свойства ScrollBars одно из значений:

None : без прокруток (по умолчанию)

Horizontal : создает горизонтальную прокрутку при длине строки, превышающей ширину текстового поля

Vertical : создает вертикальную прокрутку, если строки не помещаются в текстовом поле

Both : создает вертикальную и горизонтальную прокрутку

Автозаполнение текстового поля

Элемент TextBox обладает достаточными возможностями для создания автозаполняемого поля. Для этого нам надо привязать свойство AutoCompleteCustomSource элемента TextBox к некоторой коллекции, из которой берутся данные для заполнения поля.

Итак, добавим на форму текстовое поле и пропишем в код события загрузки следующие строки:

Автозаполнение текстового поля

Режим автодополнения, представленный свойством AutoCompleteMode , имеет несколько возможных значений:

None : отсутствие автодополнения

Suggest : предлагает варианты для ввода, но не дополняет

Append : дополняет введенное значение до строки из списка, но не предлагает варианты для выбора

SuggestAppend : одновременно и предлагает варианты для автодополнения, и дополняет введенное пользователем значение

Перенос по словам

Чтобы текст в элементе TextBox переносился по словам, надо установить свойство WordWrap равным true . То есть если одно слово не умещается на строке, то но переносится на следующую. Данное свойство будет работать только для многострочных текстовых полей.

Ввод пароля

Также данный элемент имеет свойства, которые позволяют сделать из него поле для ввода пароля. Так, для этого надо использовать PasswordChar и UseSystemPasswordChar .

Свойство PasswordChar по умолчанию не имеет значение, если мы установим в качестве него какой-нибудь символ, то этот символ будут отображаться при вводе любых символов в текстовое поле.

Свойство UseSystemPasswordChar имеет похожее действие. Если мы установим его значение в true , то вместо введенных символов в текстовом поле будет отображаться знак пароля, принятый в системе, например, точка.

Событие TextChanged

Из всех событий элемента TextBox следует отметить событие TextChanged , которое срабатывает при изменении текста в элементе. Например, поместим на форму кроме текстового поля метку и сделаем так, чтобы при изменении текста в текстовом поле также менялся текст на метке:

WPF, Поле ввода с подсказкой

Пример поля ввода с подсказкой

public static readonly DependencyProperty WatermarkTextProperty = DependencyProperty.Register( «WatermarkText» , typeof ( string ), typeof (WatermarkedTextBox), new UIPropertyMetadata( string .Empty, OnWatermarkTextChanged));

/// <summary>
/// Initializes a new instance of the <see cref=»WatermarkedTextBox»/> class with default watermark text.
/// </summary>
public WatermarkedTextBox()
: this (_defaultWatermark)
<
>

/// <summary>
/// Initializes a new instance of the <see cref=»WatermarkedTextBox»/> class.
/// </summary>
/// <param name=»watermark»>The watermark to show when value is <c>null</c> or empty.</param>
public WatermarkedTextBox( string watermark)
<
WatermarkText = watermark;
>

public static void OnWatermarkTextChanged(DependencyObject box, DependencyPropertyChangedEventArgs e)
<
//Add changed functionality here
>

* This source code was highlighted with Source Code Highlighter .

Теперь, когда создана заготовка и у нас имеются необходимые свойства и методы оперирования с подсказкой, можно приступать непосредственно к реализации. С ходу можно придумать множество вариантов реализации:
Например, можно повесить свои обработчики на установку-получение текста и выводить подсказку как обычный текст (Не раз видел подобное в различных html-формах).
Можно агреггировать TextBox , написать логику и сделать собственное отображение данных.
Но мы воспользуемся третьим, наиболее правильным методом в контексте WPF. Будем использовать стили, чтобы переопределить отображение контрола, а именно переопределим Control Template.

Сказано-сделано. Для начала, унаследуем наш класс от TextBox (вместо DependencyObject ).
Если заглянуть вот сюда, то можно увидеть следующий текст.

Это значит, что в шаблоне необходимо будет создать ScrollViewer с именем PART_ContentHost.
Итак, коварный план таков: в те моменты, когда текст внутри TextBox отсутствует — будем показывать заготовленную надпись, из отдельного TextBlock а, иначе будем притворяться обычным TextBox .

То есть где-то внутри нашего стиля будет находится:

< TextBlock x:Name =»WatermarkText» Text =»» Foreground =»Gray» Margin =»5,0,0,0″ HorizontalAlignment =»Left» VerticalAlignment =»Center» Visibility =»Collapsed» IsHitTestVisible =»False» />

* This source code was highlighted with Source Code Highlighter .

Я добавил несколько красот в виде отступов и цвета, чтобы усилия были лучше заметны.

И для него можно будет написать следующие триггеры:

< MultiTrigger.Conditions >
< Condition Property =»IsKeyboardFocusWithin» Value =»False» />
< Condition Property =»Text» Value =»» />
</ MultiTrigger.Conditions >
< Setter Property =»Visibility» TargetName =»WatermarkText» Value =»Visible» />
</ MultiTrigger >
< MultiTrigger >
< MultiTrigger.Conditions >
< Condition Property =»IsKeyboardFocusWithin» Value =»False» />
< Condition Property =»Text» Value =»» />
</ MultiTrigger.Conditions >
< Setter Property =»Visibility» TargetName =»WatermarkText» Value =»Visible» />
</ MultiTrigger >

* This source code was highlighted with Source Code Highlighter .

< Style TargetType =»» BasedOn =»>» >
< Setter Property =»Template» >
< Setter.Value >
< ControlTemplate TargetType =»» >
< Grid >
< ScrollViewer x:Name =»PART_ContentHost» />
< TextBlock x:Name =»WatermarkText» Text =»» Foreground =»Gray» Margin =»5,0,0,0″ HorizontalAlignment =»Left» VerticalAlignment =»Center» Visibility =»Collapsed» IsHitTestVisible =»False» />
</ Grid >
< ControlTemplate.Triggers >
< MultiTrigger >
< MultiTrigger.Conditions >
< Condition Property =»IsKeyboardFocusWithin» Value =»False» />
< Condition Property =»Text» Value =»» />
</ MultiTrigger.Conditions >
< Setter Property =»Visibility» TargetName =»WatermarkText» Value =»Visible» />
</ MultiTrigger >
< MultiTrigger >
< MultiTrigger.Conditions >
< Condition Property =»IsKeyboardFocusWithin» Value =»False» />
< Condition Property =»Text» Value =»» />
</ MultiTrigger.Conditions >
< Setter Property =»Visibility» TargetName =»WatermarkText» Value =»Visible» />
</ MultiTrigger >
</ ControlTemplate.Triggers >
</ ControlTemplate >
</ Setter.Value >
</ Setter >
</ Style >

* This source code was highlighted with Source Code Highlighter .

How can I add a hint text to WPF textbox?

For example, Facebook has a «Search» hint text in the Search text box when the textbox is empty.

How to achieve this with WPF text boxes??

Facebook's search textbox

14 Answers 14

You can accomplish this much more easily with a VisualBrush and some triggers in a Style :

To increase the re-usability of this Style , you can also create a set of attached properties to control the actual cue banner text, color, orientation etc.

Martin Schmidt's user avatar

what about using materialDesign HintAssist ? i’m using this which also you can add floating hint too :

i installed Material Design with Nuget Package there is installation guide in documentation link

Do it in the code-behind by setting the text color initially to gray and adding event handlers for gaining and losing keyboard focus.

Then the event handlers:

You have to create a custom control by inheriting the textbox. Below link has an excellent example about the search textbox sample. Please have a look at this

Kishore Kumar's user avatar

You can do in a very simple way. The idea is to place a Label in the same place as your textbox. Your Label will be visible if textbox has no text and hasn’t the focus.

Bonus:If you want to have default value for your textBox, be sure after to set it when submitting data (for example:»InputText»=»PlaceHolder Text Here» if empty).

I once got into the same situation, I solved it following way. I’ve only fulfilled the requirements of a hint box, you can make it more interactive by adding effects and other things on other events like on focus etc.

WPF CODE (I’ve removed styling to make it readable)

C# Code

Mohammad Mahroz's user avatar

this works also with PasswordBox . If you want to use it with TextBox , simply exchange PasswordChanged with TextChanged .

XAML:

CodeBehind:

Mat's user avatar

Another solution is to use a WPF toolkit like MahApps.Metro. It has many nice features, like a text box watermark:

StefanG's user avatar

I used the got and lost focus events:

It works well, but the text is in gray still. Needs cleaning up. I was using VB.NET

DerBesondereEin's user avatar

Most other answers including the top one have flaws in my opinion.

This solution works under all circumstances. Pure XAML, easily reusable.

I accomplish this with a VisualBrush and some triggers in a Style suggested by : sellmeadog .

@sellmeadog :Application running, bt Design not loading. the following Error comes: Ambiguous type reference. A type named ‘StaticExtension’ occurs in at least two namespaces, ‘MS.Internal.Metadata.ExposedTypes.Xaml’ and ‘System.Windows.Markup’. Consider adjusting the assembly XmlnsDefinition attributes. ‘m using .net 3.5

For WPF, there isn’t a way. You have to mimic it. See this example. A secondary (flaky solution) is to host a WinForms user control that inherits from TextBox and send the EM_SETCUEBANNER message to the edit control. ie.

Also, if you want to host a WinForm control approach, I have a framework that already includes this implementation called BitFlex Framework, which you can download for free here.

Here is an article about BitFlex if you want more information. You will start to find that if you are looking to have Windows Explorer style controls that this generally never comes out of the box, and because WPF does not work with handles generally you cannot write an easy wrapper around Win32 or an existing control like you can with WinForms.

Screenshot: enter image description here

Как подписать textbox c

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 of multiple lines. In TextBox, you are allowed to set the text associated with the TextBox by using the Text property of the TextBox. In Windows form, you can set this property in two different ways:

1. Design-Time: It is the simplest way to set the Text property of the TextBox as shown in the following steps:

  • Step 1: Create a windows form.
    Visual Studio -> File -> New -> Project -> WindowsFormApp
  • Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need.
  • Step 3: After drag and drop you will go to the properties of the TextBox control to set the Text property of the TextBox.

2. Run-Time: It is a little bit tricky than the above method. In this method, you can set the Text property of the TextBox programmatically with the help of given syntax:

Here, the text is represented in the form of String. Following steps are used to set the Text property of the TextBox:

  • Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.
  • Step 2 : After creating TextBox set the Text property of the TextBox provided by the TextBox class.
  • Step 3 : And last add this textbox control to from using Add() method.

Читать:
Как отключить обновление adobe flash player windows 10

Related Posts