【发布时间】:2011-06-16 18:29:30
【问题描述】:
当文本框有值且组合框有选定项时,如何启用(反之禁用)按钮?
如何设置绑定以使按钮适当地禁用/启用?
【问题讨论】:
当文本框有值且组合框有选定项时,如何启用(反之禁用)按钮?
如何设置绑定以使按钮适当地禁用/启用?
【问题讨论】:
这不是你应该思考的方式。 WPF 鼓励使用 MVVM,因此您应该准备您的 VM 类,以便它具有您应该绑定到的适当属性(也可能是模型类)。不要将逻辑/验证逻辑放入您的 GUI。
【讨论】:
为什么不考虑使用命令绑定?请参阅/尝试以下简化示例:
<Window.CommandBindings>
<CommandBinding Command="Save" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<StackPanel>
<TextBox Name="TextBox1"/>
<Button Content="Save" Command="Save"/>
</StackPanel>
CommandBinding 有一个属性 [CanExecute],可用于在后面的代码中启用/禁用按钮:
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = (this.TextBox1.Text == "test");
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
// put your command-logic here
}
在本例中,您必须输入值“test”以启用按钮并执行您的命令逻辑。
【讨论】:
将按钮绑定到命令(例如 Save-Command)
将 TextBox.Text 绑定到属性(例如 string MyTextBoxText)
将 ComboBox 的 SelectedItem 绑定到属性(甚至 itemSource)(例如 object MySelectedItem)
该命令的 CanExecute 代码如下:
return !string.IsNullOrWhiteSpace(MyTextBoxText) && (MySelectedItem != null);
【讨论】:
另一种方法是在要启用/禁用的按钮上使用 MultiBinding 和 Converter
<Window ... xmlns:local="...">
<Window.Resources>
<local:MyMultiValueConverter x:Key="MyMultiValueConverter" />
</Window.Resources>
...
<ComboBox x:Name="myComboBox">...</ComboBox>
<TextBox x:Name="myTextBox">...</TextBox>
...
<Button Content="My Button">
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource MyMultiValueConverter}">
<Binding ElementName="myComboBox" Path="SelectedValue" />
<Binding ElementName="myTextBox" Path="Text" />
</MultiBinding>
</Button.IsEnabled>
</Button>
...
</Window>
您需要创建IMultiValueConverter interface 的实现,它测试 ComboBox.SelectedValue 和 TextBox.Text 属性的值并返回 true 或 false,然后将其分配给 Button.IsEnabled 属性。这是一个简单的转换器,但您需要确保根据您的特定需求定制一个:
public class MyMultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values == null)
return false;
return values.All(c => c is String ? !String.IsNullOrEmpty((string)c) : c != null);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
虽然这种方法确实有效,但我倾向于同意其他答案,因为您应该尽可能使用命令而不是多重绑定和转换器。
【讨论】: