简体   繁体   中英

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.

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.

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