How can I clear my TextBox when it is focused? I want to do this in MVVM way. If it has meaning - my TextBox control has Text property binded with some property in ViewModel. TextBox displays sth like "50,30 zł". It is uncomfortable for user to select text, delete it and write new text, so I want to clear old Text when Texbox is focused.
相关问题
- Carriage Return (ASCII chr 13) is missing from tex
- VNC control for WPF application
- WPF Binding from System.Windows.SystemParameters.P
- XAML: Applying styles to nested controls
- How can I add a horizontal line (“goal line”) for
textBox1.Clear();
It Clears the Content in textBox
You can write your own behavior or even control. I will try to explain the first one:
First, you should a add reference to the System.Windows.Interactivity assembly.
Then create a class (which will be the behavior) and derive it from System.Windows.Interactivity.Behavior< System.Windows.Controls.TextBox>, where templated (generic type) parameter is a control which should behave as I described.
For example:
Next, put the following reference declaration in your parent window in xaml
Finally add the behavior to the appropriate UI element(TextBox in our case):
Great answer from @Dmitry Martovoi.
This is the same solution, using an Attached Property (rather than a Blend Behavior). Attached behaviors make for simpler XAML, but less simple C#, whereas Blend behaviors are the opposite.
XAML:
Add
behaviors:MyTextBox.MyClearOnFocusedIfTextEqualsSearch="True"
to the TextBox to make it clear itself if it receives focus, and it containsSearch
.And the attached property:
It took me a few minutes to write this attached behavior. ReSharper has a great macro to do this, if you type
attachedProperty
, it will fill out most of this code for you.