简体   繁体   中英

MultiBinding Fallback value on unsetvalue

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(ie, 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM