I have a Button and a TextBox in my WPF app. How can I make the Button not enabled until the user enters some text in the TextBox?
相关问题
- 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
By code:
By XAML:
You could subscribe to the
TextChanged
event on theTextBox
and if the text is empty set theButton
to disabled. Or you could bind theButton.IsEnabled
property to theTextBox.Text
property and use a converter that returns true if there is any text and false otherwise.I know this isn't as elegant as the other posts, but it's a more straightforward xaml/codebehind example of how to accomplish the same thing.
Xaml:
CodeBehind:
This should do it:
In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel
Text
that is bound to your TextBox and you would have a ICommand propertyApply
(or similar) that is bound to the button:The
ICommand
interface has a MethodCanExecute
that is where you returntrue
if (!string.IsNullOrWhiteSpace(this.Text)
. The rest is done by WPF for you (enabling/disabling, executing the actual command on click).The linked article explains it in detail.