I'm looking for a way to specify a fallback value if any of the bindings within a multibinding fail.

Here is the case where the binding succeeds(i.e, A and B are valid paths)

<MultiBinding Converter="{local:MultiConverter}">
    <Binding Path="A"/>
    <Binding Path="B"/>
</MultiBinding>

Here, is a case where it fails(path to 'B' is broken)

<MultiBinding Converter="{local:MultiConverter}">
    <Binding Path="A"/>
    <Binding Path="Bb"/>
</MultiBinding>

which passes in a value of {DependencyProperty.UnsetValue} for value[1] of the converter. I was hoping I could do something like the following :

<MultiBinding Converter="{local:MultiConverter}" FallbackValue="Egg">
    <Binding Path="A"/>
    <Binding Path="Bb"/>
</MultiBinding>

but, unfortunately, the convertor is still called with the unset value.

Whilst I'm aware that you can do the following

<MultiBinding Converter="{local:MultiConverter}">
    <Binding Path="A"/>
    <Binding Path="Bb" FallbackValue="Egg"/>
</MultiBinding>

It's not what I want. I want to specify the fallback for the entire multibinding to be X, if any of the subbindings fail. I don't want to have to specify a fallback for each component.

Currently, I'm resorting to the following, ... but I'd like to specify the fallback on the multibinding, not the converter.

public class MultiConverter : MarkupExtension, IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.Any(e => e == DependencyProperty.UnsetValue))
        {
            return "failed!";
        }
        return values[0].ToString() + values[1].ToString();
    }

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

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}
有帮助吗?

解决方案

Maybe use the TargetNullValue to return null from the converter instead of the "failed!"

<MultiBinding Converter="{local:MultiConverter}" TargetNullValue="Failed!">
    <Binding Path="A"/>
    <Binding Path="Bb" />
</MultiBinding>

This way you do the check in the converter and if the converter returns null because of any binding error's your result would pick the TargetNullvalue

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top