Search code examples
wpfmultibinding

How does ComboBox MultiBinding bind to SelectedItem's property


I am using MultiBinding for a ComboBox. One of the parameters I want to bind is the SelectedItem's SelectedName. Here SelectedName is string type.

If NOT MultiBinding, I have this that works well:

<ComboBox Background="{Binding SelectedItem.SelectedName, 
        RelativeSource={RelativeSource Self}, Converter={StaticResource MyConverter}}">

But in MultiBinding when I tried to bind to SelectedItem.SelectedName it reports

Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.String'.

This is my code:

<ComboBox.Background>
    <MultiBinding Converter="{StaticResource MyMultiBindingConverter}">
        <Binding .../>
        <Binding RelativeSource="{RelativeSource Self}" Path="SelectedItem.SelectedName"/> //this line fails
    </MultiBinding>
</ComboBox.Background>

How can I make it correct? Thanks.

Updated information:

The ComboBox does not have a default SelectedItem. When I use MyConverter, If I have not selected an item, the breakpoint in Convert method will not be hit. After I selected an item the breakpoint is hit which is the behavior I want.

However when I use MyMultiBindingConverter the situation is completely inverse - The breakpoint will be hit on UI load and will not be hit after I selected an item.


Solution

  • You should check whether you get a string in your Convert method:

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.Length < 2)
            return Binding.DoNothing;
    
        string selectedName = values[1] as string;
        if (string.IsNullOrEmpty(selectedName))
            return Binding.DoNothing;:
    
        //...
    }
    

    You can't assume that the SelectedItem.SelectedName property returns a value each time the Convert method is called.