MultiBinding转换器绑定

时间:2014-02-06 23:14:28

标签: .net wpf imultivalueconverter

MultiBinding转换器的问题
我知道两次发送相同的值是没有意义的 我这样做是为了隔离那个单一的约束力 在转换器中,我得到了一个关于强制转换为bool的错误 值是

  

{DependencyProperty.UnsetValue}

但“RWnet”是一个bool

<ContentPresenter Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"
        x:Name="fieldTemplateDetail"
        Content="{Binding}"
        ContentTemplateSelector="{StaticResource fieldTemplateSelector}">
    <ContentPresenter.Visibility>
        <MultiBinding Converter="{StaticResource visabilityConverterTwoBool}">
            <Binding Path="RWnet" />
            <Binding Path="RWnet" />
        </MultiBinding>
    </ContentPresenter.Visibility>
</ContentPresenter>

public class VisabilityConverterTwoBool : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null) return Visibility.Visible;
        if (values.Length != 2) return Visibility.Visible;
        try
        {
            if ((bool)values[0] == false) return Visibility.Collapsed;
            if ((bool)values[1] == false) return Visibility.Collapsed;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message, "VisabilityConverterTwoBool");
            Debug.WriteLine(values[0].ToString());
            Debug.WriteLine(values[1].ToString());
        }
        return Visibility.Visible;
    }

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

如果我发送实际多重绑定的另一半,它可以工作 (错误的结果,但没有错误)

<Binding ElementName="cbEditMode" Path="IsChecked" />

但是这很好用 RWnet是一个bool

<ContentPresenter Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"
        Visibility="{Binding Path=RWnet, Converter={StaticResource bvc}}"
        x:Name="fieldTemplateDetail"
        Content="{Binding}"
        ContentTemplateSelector="{StaticResource fieldTemplateSelector}"/>

<BooleanToVisibilityConverter x:Key="bvc" />

对于McGarnagle来说这是数据上下文

<ListBox  Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" x:Name="lbCurDocFields" 
            ItemsSource="{Binding Source={StaticResource curDocFields}}" LostFocus="lbCurDocFields_LostFocus"

1 个答案:

答案 0 :(得分:1)

根据您对数据上下文的连接方式,无法保证在您预期的情况下准备好绑定。完全验证输入,它应该解决问题:

if (values.Length != 2 && values[0] as bool? == null || values[1] as bool? == null)
    return Visibility.Visible;