简体   繁体   English

C# WPF IsEnabled 使用多个绑定?

[英]C# WPF IsEnabled using multiple bindings?

I have a WPF xaml file describing a section of a GUI and I'd like the enabling/disabling of a particular control to be dependent on two others.我有一个描述 GUI 部分的 WPF xaml 文件,我希望特定控件的启用/禁用依赖于其他两个控件。 The code looks something like this at the moment:代码现在看起来像这样:

<ComboBox Name="MyComboBox"
          IsEnabled="{Binding ElementName=SomeCheckBox, Path=IsChecked}"/>

But I'd like it to be dependant on another checkbox as well so something like:但我希望它也依赖于另一个复选框,例如:

<ComboBox Name="MyComboBox"
          IsEnabled="{Binding ElementName=SomeCheckBox&AnotherCheckbox, Path=IsChecked}"/>

What's the best way to go about that? go 的最佳方法是什么? I can't help feeling I'm missing something obvious or going about this the wrong way?我不禁觉得我遗漏了一些明显的东西或以错误的方式解决这个问题?

You can use a MultiBinding with a converter which implements IMultiValueConverter . 您可以将MultiBinding与实现IMultiValueConverter的转换器IMultiValueConverter

Just to give an answer you can (almost) copy&paste: 只需给出答案,您就可以(几乎)复制并粘贴:

Static resource needed: 需要的静态资源:

<converterNamespace:BooleanAndConverter x:Key="booleanAndConverter" />

The ComboBox: ComboBox:

<ComboBox Name="MyComboBox">
  <ComboBox.IsEnabled>
    <MultiBinding Converter="{StaticResource booleanAndConverter}">
      <Binding ElementName="SomeCheckBox" Path="IsChecked" />
      <Binding ElementName="AnotherCheckbox" Path="IsChecked"  />
    </MultiBinding>
  </ComboBox.IsEnabled>
</ComboBox>

The code for the converter: 转换器的代码:

namespace ConverterNamespace
{
    public class BooleanAndConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            foreach (object value in values)
            {
                if ((value is bool) && (bool)value == false)
                {
                    return false;
                }
            }
            return true;
        }
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException("BooleanAndConverter is a OneWay converter.");
        }
    }
}

You can also try shorter version of the same: 您也可以尝试相同的较短版本:

public class BooleanAndConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return values.OfType<IConvertible>().All(System.Convert.ToBoolean);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

public class BooleanOrConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return values.OfType<IConvertible>().Any(System.Convert.ToBoolean);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

and, of course, you may need the converters for visibility, too: 当然,您也可能需要转换器以实现可见性:

public class BooleanOrToVisibilityConverter : IMultiValueConverter
{
    public Visibility HiddenVisibility { get; set; }

    public bool IsInverted { get; set; }

    public BooleanOrToVisibilityConverter()
    {
        HiddenVisibility = Visibility.Collapsed;
        IsInverted = false;
    }

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        bool flag = values.OfType<IConvertible>().Any(System.Convert.ToBoolean);
        if (IsInverted) flag = !flag;
        return flag ? Visibility.Visible : HiddenVisibility;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class BooleanAndToVisibilityConverter : IMultiValueConverter
{
    public Visibility HiddenVisibility { get; set; }

    public bool IsInverted { get; set; }

    public BooleanAndToVisibilityConverter()
    {
        HiddenVisibility = Visibility.Collapsed;
        IsInverted = false;
    }

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        bool flag = values.OfType<IConvertible>().All(System.Convert.ToBoolean);
        if (IsInverted) flag = !flag;
        return flag ? Visibility.Visible : HiddenVisibility;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

I believe you may have to use a MultiBinding with a MultiValueConverter. 我相信您可能必须使用MultiBinding与MultiValueConverter。 See here: http://www.developingfor.net/wpf/multibinding-in-wpf.html 见这里: http//www.developingfor.net/wpf/multibinding-in-wpf.html

Here is a directly related example: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/5b9cd042-cacb-4aaa-9e17-2d615c44ee22 这是一个直接相关的例子: http//social.msdn.microsoft.com/Forums/en-US/wpf/thread/5b9cd042-cacb-4aaa-9e17-2d615c44ee22

As extension to qqbenq's answer: 作为qqbenq答案的扩展:

Added the function to handle the Count of a Collection for example if you want to check if some item of a ListView is selected. 添加了处理Collection的Count的函数,例如,如果要检查是否选择了ListView某个项目。

Converter: 转换器:

public class IsEnabledConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        foreach (var value in values)
        {
            switch (value)
            {
                case bool b when !b:
                case int i when i == 0:
                    return false;
            }
        }

        return true;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return null;
    }
}

Namespace <theNamespace:IsEnabledConverter x:Key="IsEnabledConverter"/> 命名空间 <theNamespace:IsEnabledConverter x:Key="IsEnabledConverter"/>

Button 按键

<Button x:Name="MyButton">
    <Button.IsEnabled>
        <MultiBinding Converter="{StaticResource IsEnabledConverter}">
            <Binding ElementName="MyListView" Path="SelectedItems.Count"/>
            <Binding ElementName="MyCheckBox" Path="IsChecked"/>
        </MultiBinding>
    </Button.IsEnabled>
</Button>

When you don't want to use MultiBinding当您不想使用 MultiBinding 时

public class AndEnabledTextBox : TextBox
{
    public static readonly DependencyProperty AndEnabled1SubProperty =
        DependencyProperty.Register(nameof(AndEnabled1), typeof(bool), typeof(AndEnabledTextBox), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnAndEnabledPropertyChanged)));
    public static readonly DependencyProperty AndEnabled2SubProperty =
        DependencyProperty.Register(nameof(AndEnabled2), typeof(bool), typeof(AndEnabledTextBox), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnAndEnabledPropertyChanged)));
    public bool AndEnabled1 { get { return (bool)GetValue(AndEnabled1SubProperty); } set { SetValue(AndEnabled1SubProperty, value); } }
    public bool AndEnabled2 { get { return (bool)GetValue(AndEnabled2SubProperty); } set { SetValue(AndEnabled2SubProperty, value); } }
    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);
        IsEnabled = AndEnabled1 && AndEnabled2;
    }
    protected static void OnAndEnabledPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        AndEnabledTextBox textBox = (AndEnabledTextBox)obj;
        textBox.IsEnabled = textBox.AndEnabled1 && textBox.AndEnabled2;
    }
}

XMAL is more simplified when you use inherited controls.当您使用继承的控件时, XMAL更加简化。

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp1">
    <StackPanel>
        <ToggleButton x:Name="switch1" Content="{Binding ElementName=switch1, Path=IsChecked}"/>
        <ToggleButton x:Name="switch2" Content="{Binding ElementName=switch2, Path=IsChecked}"/>
        <local:AndEnabledTextBox Text="TEXT"
                                 AndEnabled1="{Binding ElementName=switch1, Path=IsChecked, Mode=OneWay}"
                                 AndEnabled2="{Binding ElementName=switch2, Path=IsChecked, Mode=OneWay}"/>
    </StackPanel>
</Window>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM