WPF MultiBinding 和 Converter

效果如图
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

上一篇:皮肤代码


下一篇:FDD与TDD的区别