Search code examples
wpfcomboboxmultibinding

ComboBox Multibinding


I'm pretty new to WPF. I'm having a problem with a ComboBox

        <ComboBox Grid.Column="2" Grid.Row="5" x:Name="ddlLocation" ItemsSource="{Binding Users.Locations}" Text="&lt;None Selected&gt;" IsEditable="True" IsReadOnly="True" SelectedValue="{Binding Users.SelectedUser.Location}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding StringFormat="{}{0} - {1}">
                            <Binding Path="Name" />
                            <Binding Path="ShortName" />
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <!--<ComboBox.SelectionBoxItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding StringFormat="{}{0} - {1}">
                            <Binding Path="Name" />
                            <Binding Path="ShortName" />
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>
            </DataTemplate>
        </ComboBox.SelectionBoxItemTemplate>-->
    </ComboBox>

If I do this I get the typename in the selection box. It seems like I should be able to use the SelectionBoxItemTemplate but it tells me SelectionBoxItemTemplate doesn't have an accessible setter. How would you do this?


Solution

  • Looks like this is a result of having IsEditable="True" which I would suggest removing, as you also have IsReadOnly="True"

    Regarding the Text property --- a default value when nothing is selected... I'll just put this out there but am hoping someone has a better solution... I didn't see anything at a quick look online.

    Include the namespace

    xmlns:conv="clr-namespace:StackOverflow.Converters"
    

    Some xaml

    <ComboBox ... IsEditable="{Binding SelectedItem, RelativeSource={RelativeSource Self}, Converter={StaticResource NullBoolConverter}, FallbackValue=False}">
        <ComboBox.Resources>
            <conv:NullBoolConverter x:Key="NullBoolConverter" />
        </ComboBox.Resources>
    

    Converter class

    namespace StackOverflow.Converters
    {
        class NullBoolConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                return value == null;
            }
            ....
         }
    }