WPF MultiBinding 和 Converter

效果如图

上图中,最下方TextBlock控件的Visibility属性由ComboBox和CheckBox的值共同决定,当ComboBox选择“是”,CheckBox被勾选时,Visibility属性为可见的,其余情况为不可见。

关键代码

<local:MultiBinding2Converter x:Key="MultiBinding2Converter"></local:MultiBinding2Converter>
<TextBlock Text="判断是否显示的文字">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Visibility">
                <Setter.Value>
                    <MultiBinding Converter="{StaticResource MultiBinding2Converter}" ConverterParameter="YourParameter">
                        <Binding ElementName="comboBox" Path="SelectedItem"/>
                        <Binding ElementName="checkBox" Path="IsChecked"/>
                    </MultiBinding>
                </Setter.Value>
            </Setter>
        </Style>
    </TextBlock.Style>
</TextBlock>
public class MultiBinding2Converter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var selectItem = values[0] as ComboBoxItem;
        var isChecked = values[1] as bool?;
        //此处不需要该参数,这里只是展示Converter传参一个固定字符串
        var para = parameter as string;
        if(selectItem!=null && selectItem.Tag.ToString()=="1" &&
            isChecked.HasValue && isChecked.Value)
            return Visibility.Visible;
        return Visibility.Collapsed;
    }

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

示例代码

MultiBinding2

posted @ 2020-09-07 21:10  Lulus  阅读(781)  评论(0编辑  收藏  举报