63

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?

2 Answers 2

126

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}" />
Sign up to request clarification or add additional context in comments.

15 Comments

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.
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.
@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...
@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.
@Mark, you can do something like that: gist.github.com/thomaslevesque/3713bed71a486d02858a, bind CheckBox.IsChecked to IsTextBoxDisabled, and TextBox.IsEnabled to IsTextBoxEnabled
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.