Given:
WPF 4.0 desktop-based application. Basic input form with two TextBox fields and submit button.
XAML-code:
<Label Content="Username" />
<TextBox x:Name="Form_UserName" />
<Label Content="Password" />
<TextBox x:Name="Form_Password" />
<Button x:Name="Submit"
Click="Form_Submit_Button_Click"
Content="Submit" />
Task:
Implement logic where submit button is enabled if and only if two TextBox fields are filled.
The classical way to solve this issue is a use of event handlers such as onLostFocus() or something like that, where we can control condition of this fields every time when user switch focus from the field.
But since my project is WPF-based, I prefer to use a native way to work with forms — data binding mechanism. I read some articles from this site and MSDN too about form validation, but in almost all examples is proposed to use MVVM framework and I would like to implement it without any framework.
Also, I tried to play with IMultiValueConverter but no worked result is received.
How to solve the problem with the data binding as simple as possible (I’m only starting with WPF)?
This can be easily done using the WPF validation mechanisms. First since you want to follow the WPF architecture I would reccomend you to use the WPF Command model.
Now to implement your functionality, you can add a
CommandBindingto the Window/UserControl or to theButtonitself:Now you can subscribe to the
CanExecuteevent to enable or disable your button based on your validation logic. I recommend these reads before you continue:Validation in Windows Presentation Foundation
Using Custom Validation Rules in WPF
The simplest way to do your requirement is as given below:
XAMLCode behindHope this helps.