使用 MVVM 根据 WPF 中的复选框选择启用/禁用文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4584442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enable/disable textbox based on checkbox selection in WPF using MVVM
提问by aliensurfer
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 表单,其中包含多达 40 个文本框,每个文本框都有一个复选框。每个文本框都应根据其相应复选框的值启用/禁用。我已经看到了我们可以ICommand
用来实现这一目标的解决方案,但是如何在没有 40 个ICommand
实现的情况下处理 40 个单独的案例?
回答by Thomas Levesque
Just bind the IsEnabled
property of the TextBox
to the IsChecked
property of the CheckBox
:
只需将 的IsEnabled
属性绑定TextBox
到 的IsChecked
属性CheckBox
:
<CheckBox Name="checkBox1" />
<TextBox IsEnabled="{Binding ElementName=checkBox1, Path=IsChecked}" />
回答by Wesley Kenis
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
如果您有 40 个这样的控件,我将创建一个包含复选框和文本框的新控件。您可以使用该新控件而无需实现 40 个命令,相反,您的新控件只有一个命令实现。这也是更少的代码维护作为额外的好处