How to boolean && two visibility converters

孤街醉人 提交于 2019-11-28 09:36:38

You could use a MultiBinding together with a short, hand made IMultiValueConverter.

Example:

<StackPanel>
    <StackPanel.Resources>
        <local:MultiBooleanToVisibilityConverter x:Key="Converter" />
    </StackPanel.Resources>
    <CheckBox x:Name="Box1" />
    <CheckBox x:Name="Box2" />
    <TextBlock Text="Hidden Text">
        <TextBlock.Visibility>
            <MultiBinding Converter="{StaticResource Converter}">
                <Binding ElementName="Box1"
                            Path="IsChecked" />
                <Binding ElementName="Box2"
                            Path="IsChecked" />
            </MultiBinding>
        </TextBlock.Visibility>
    </TextBlock>                   
</StackPanel>

... and the converter ...

class MultiBooleanToVisibilityConverter : IMultiValueConverter
{
    public object Convert(object[] values,
                            Type targetType,
                            object parameter,
                            System.Globalization.CultureInfo culture)
    {
        bool visible = true;
        foreach (object value in values)
            if (value is bool)
                visible = visible && (bool)value;

        if (visible)
            return System.Windows.Visibility.Visible;
        else
            return System.Windows.Visibility.Hidden;
    }

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

Late to the party here but an easier solution is to just wrap the control in another control. I prefer this to having lots of Converters that do different things.

<Border Visibility="{Binding Value1, Converter={convertersDF:Converter_ValueToVisibility}}">
 <ComboBox Visibility="{Binding Value2, Converter={convertersDF:Converter_ValueToVisibility}}"/>
</Border>

One thing that came to mind is, perhaps, instead of two different boolean fields, a single bit field created by ORing together updatedField and allowedField. Then you can have three value converters, all operating on the same field.

Or just calculate another field in your data model that does the ANDing there. That's probably more efficient (in terms of runtime).

You could pass an array of two objects to the converter in the ConverterParameter - constructing the array in XAML.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!