其他分享
首页 > 其他分享> > 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

标签:Converter,object,Visibility,public,isChecked,var,WPF,parameter,MultiBinding
来源: https://blog.csdn.net/sinat_23050697/article/details/110472308