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?
Add a comment
|
2 Answers
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}" />
15 Comments
aliensurfer
Yes, I just tried this after posting the question. This works for me. It's just that I was trying to avoid naming each checkbox to achieve pure MVVM, but I think I'll have to make an exception. Thanks.
Dabblernl
I agree. Don't do this through MVVM. This enable/disable thingy is a pure User Interface design decision and has nothing to do with the underlying data of your application.
Thomas Levesque
@Prakash: What makes you think that naming a checkbox isn't "pure" MVVM? Nothing in MVVM says you shouldn't give name to UI items...
aliensurfer
@Thomas True. An ideal MVVM implementation wouldn't have any names for the data-bound controls. I realize that I can have names for the checkboxes as they're not bound to any data. What I require is pure UI functionality.
Thomas Levesque
@Mark, you can do something like that: gist.github.com/thomaslevesque/3713bed71a486d02858a, bind
CheckBox.IsChecked to IsTextBoxDisabled, and TextBox.IsEnabled to IsTextBoxEnabled |
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