WPF Binding FallbackValue set to Binding

前端 未结 3 1096
谎友^
谎友^ 2021-01-31 15:43

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

I\'m trying to do something like this:

相关标签:
3条回答
  • 2021-01-31 16:19

    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>
    
    0 讨论(0)
  • 2021-01-31 16:30

    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

    0 讨论(0)
  • 2021-01-31 16:35

    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>
    
    0 讨论(0)
提交回复
热议问题