39

Is there a way to have another binding as a fallback value?

I'm trying to do something like this:

<Label Content="{Binding SelectedItem.Name, ElementName=groupTreeView,
                         FallbackValue={Binding RootGroup.Name}}" />

If anyone's got another trick to pull it off, that would be great.

Palec
  • 12,743
  • 8
  • 69
  • 138
HaxElit
  • 3,983
  • 7
  • 34
  • 43

3 Answers3

82

What you are looking for is something called PriorityBinding (#6 on this list)

(from the article)

The point to PriorityBinding is to name multiple data bindings in order of most desirable to least desirable. This way if the first binding fails, is empty and/or default, another binding can take it's place.

e.g.

<TextBox>
    <TextBox.Text>
        <PriorityBinding>
            <Binding Path="LastNameNonExistant" IsAsync="True" />
            <Binding Path="FirstName" IsAsync="True" />
        </PriorityBinding>
    </TextBox.Text>
</TextBox>
kiwipom
  • 7,639
  • 37
  • 37
  • 31
    The problem is that PriorityBinding treats a null string as a successful binding – Shimmy Weitzhandler Feb 08 '10 at 20:39
  • 8
    from the [MSDN](https://msdn.microsoft.com/en-us/library/system.windows.data.prioritybinding%28v=vs.110%29.aspx): `The value DependencyProperty.UnsetValue is not considered a successful return value.` - so just use a Converter on your binding that returns that property if your value is null. @Shimmy – Steffen Winkler Nov 05 '15 at 09:14
4

If you run into problems with binding to null values and PriorityBinding (as Shimmy pointed out) you could go with MultiBinding and a MultiValueConverter like that:

public class PriorityMultiValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.FirstOrDefault(o => o != null);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Usage:

<TextBox>
    <TextBox.Text>
        <MultiBinding Converter="{StaticResource PriorityMultiValueConverter}">
            <Binding Path="LastNameNull" />
            <Binding Path="FirstName" />
        </MultiBinding>
    </TextBox.Text>
</TextBox>
Sven
  • 11,442
  • 2
  • 16
  • 20
3

Under what conditions would you like it to use the Fallback value? How would you determine that a binding has failed? A binding is still valid even if it's bound to a null value.

I think a good bet may be to use a converter to convert to a default value if the binding returns null. I'm not sure how you could default to another bound value though.

Check out converters here

James Hay
  • 12,580
  • 8
  • 44
  • 67
  • In my case, it's where I'm 90%+ sure that the `DataContext` will have a specific property on it, but I want to fall back to calling `.ToString()` where/if it doesn't. – tobriand Feb 08 '17 at 13:53