如何根据多个其他控件中的值启用(并反向禁用)按钮?

时间:2011-06-16 18:29:31

标签: wpf binding

如果文本框有值,并且组合框中包含所选项目,如何启用(并反向禁用)按钮?

如何设置绑定以使按钮适当地禁用/启用?

4 个答案:

答案 0 :(得分:1)

这不是你应该想的方式。 WPF鼓励使用MVVM,因此您应该准备VM类,以便它具有您应该绑定的适当属性(并且可能也是模型类)。不要将逻辑/验证逻辑放入GUI中。

答案 1 :(得分:1)

为什么不考虑使用命令绑定?请参阅/尝试以下简化示例:

<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”以启用按钮并执行命令逻辑。

答案 2 :(得分:0)

将按钮绑定到命令(例如Save-Command)
将TextBox.Text绑定到属性(例如string MyTextBoxText
将ComboBox的SelectedItem绑定到属性(甚至是itemSource)(例如object MySelectedItem
该命令的CanExecute具有如下代码:

return !string.IsNullOrWhiteSpace(MyTextBoxText) && (MySelectedItem != null);

答案 3 :(得分:0)

另一种方法是在要启用/禁用

的按钮上使用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();
    }
}

虽然这种方法确实有效,但我倾向于同意其他答案,因为你应该在可能的情况下使用命令而不是多个绑定和转换器。

相关问题