XAML only WPF Watermarked TextBox
Translated by [email protected] Author:[email protected]
A lot of the examples I found on how to add a watermark to a TextBox involve a significant amount of code-behind, handling text changed events, or making use of a customIValueConverterorIMultiValueConverter. In this article, I'll show how to add a watermark to a TextBox by only using XAML markup.
A demonstration project I recently worked on was pre-setting the text of a textbox as kind of a poor-man's watermark. But when you started typing in the box, you have to first clear away the default value. That's not a watermark, that's just annoying. I wanted to fix this, but I didn't want to write a bunch of C# code to make it happen. I knew it could be done in XAML.
Using the code
Let's just jump right to it
First we wrap everthing in aGrid. We'll use this as a container to define our overall layout. Then we add ourTextBoxfor user input, and ourTextBlockas our watermark. Since we don't specify row and column definitions, these controls will overlap - and we want that; a watermark should visually appear on top of a textbox. On our TextBlock however, we don't want it be included in any hit test results, so we'll set the IsHitTestVisible property to false.
For theTextBlock's style, we'll default it to collapsed, and then set it to visible when our DataContext's Text property does not have content AND when the TextBox does not have keyboard focus.
And that's it! No converters, no extensions, just pure XAML.
File listTips: You can preview the content of files by clicking file names^_^
|WatermarkExample.sln||1,017.00 B||2015-03-04 22:11|
|App.config||189.00 B||2015-03-04 22:11|
|App.xaml||587.00 B||2015-03-04 22:11|
|App.xaml.cs||349.00 B||2015-03-04 22:11|
|MainWindow.xaml||2.18 kB||2015-03-04 22:11|
|MainWindow.xaml.cs||682.00 B||2015-03-04 22:11|
|packages.config||296.00 B||2015-03-04 22:11|
|AssemblyInfo.cs||2.24 kB||2015-03-04 22:11|
|Resources.Designer.cs||2.79 kB||2015-03-04 22:11|
|Resources.resx||5.48 kB||2015-03-04 22:11|
|Settings.Designer.cs||1.08 kB||2015-03-04 22:11|
|Settings.settings||201.00 B||2015-03-04 22:11|
|MainViewModel.cs||1.60 kB||2015-03-04 22:11|
|ViewModelLocator.cs||1.36 kB||2015-03-04 22:11|
|WatermarkExample.csproj||5.53 kB||2015-03-04 22:11|
(Add your comment, get 0.1 Point)
- Page 1
- Total 1