Enable/disable textbox based on checkbox selection in WPF using MVVM

WpfMvvm

Wpf Problem Overview


I have a WPF form with as many as 40 textboxes, with a checkbox for each. Each textbox should be enabled/disabled based on the value of its corresponding checkbox. I've seen solutions where we can use ICommand to achieve this, but how do I handle 40 individual cases without having 40 ICommand implementations?

Wpf Solutions


Solution 1 - Wpf

Just bind the IsEnabled property of the TextBox to the IsChecked property of the CheckBox:

<CheckBox Name="checkBox1" />
<TextBox IsEnabled="{Binding ElementName=checkBox1, Path=IsChecked}" />

Solution 2 - Wpf

if you have 40 controls like this, I would create a new control containing the checkbox and the textbox. The you can use that new control without the need to implement 40 commands, instead your new control has a single command implementation. and this is also less code to maintain as additional benefit

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaliensurferView Question on Stackoverflow
Solution 1 - WpfThomas LevesqueView Answer on Stackoverflow
Solution 2 - WpfWesley KenisView Answer on Stackoverflow