Search code examples
c#wpfxamlconvertersmultibinding

How to prevent MultiBinding chain through null object


I have the following XAML code:

        <TextBox Text="Image.Bytes" IsReadOnly="True"/>
        <TextBox IsReadOnly="True">
             <TextBox.Text>
                <MultiBinding Converter="{StaticResource ConcatTextConverter}" ConverterParameter="x">
                    <Binding Path="Image.Width"/>
                    <Binding Path="Image.Height"/>
                </MultiBinding>
            </TextBox.Text>
        </TextBox>
        

The ConcatTextConverter is a simple converter doing as follows:

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string result = string.Empty;
        string separator = parameter?.ToString() ?? "";

        if(values?.Any() == true)
        {
            result = string.Join(separator, values);
        }

        return result;
    }

The Problem happens, when property "Image" is null. The first textbox just shows nothing as whished.

The second, however, shows "DependencyProperty.UnsetValue}x{DependencyProperty.UnsetValue}"

The values given into the converter are of type: values[0].GetType() {Name = "NamedObject" FullName = "MS.Internal.NamedObject"} System.Type {System.RuntimeType} Unfortunately I can't acces to this type MS.Internal.NamedObject to filter it in the converter in case of happening.

Now the Question is: What is the best way to prevent calling the converter in first place, when some object in the binding chain is null? - Or secondly: what would be the best approach to identify such "values" in the converter?


Solution

  • You can't avoid that the converter is called, but you can check whether all of the Bindings did produce a value.

    public object Convert(
        object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string result = string.Empty;
        string separator = parameter?.ToString() ?? "";
    
        if (values.All(value => value != DependencyProperty.UnsetValue))
        {
            result = string.Join(separator, values);
        }
    
        return result;
    }