Search code examples
c#wpfcomboboxbinding

Bind multiple variables from a list to one combobox


I just started learning WPF and C#.

Consider:

private void TransferAccountButtonClick(object sender, RoutedEventArgs e)
{
    List<Client> allClients = Client.JsonToList();
    TransferStackPanel.Visibility = Visibility.Visible;

    TransferNameCombobox.DataContext = allClients;
    TransferNameCombobox.DisplayMemberPath = "surname";
}

I need to display multiple fields in a combo box. Something like

TransferNameCombobox.DisplayMemberPath = "surname" + " " + "name" + " " + "patronymic";

If I do this it will show empty fields. I understand that "surname" is not a string, but I don't understand how to do it.

In XAML, I only have:

<ComboBox x:Name="TransferNameCombobox" ItemsSource="{Binding}"/>

Solution

  • Instead of TransferNameCombobox.DataContext = allClients; make it TransferNameCombobox.ItemsSource = allClients; and delete TransferNameCombobox.DisplayMemberPath = "surname";

    And then in the xaml, use this MultiBinding structure:

            <ComboBox x:Name="TransferNameCombobox">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock>
                            <TextBlock.Text>
                                <MultiBinding StringFormat="{}{0}, {1}, {2}">
                                    <Binding Path="surname"/>
                                    <Binding Path="name"/>
                                    <Binding Path="patronymic"/>
                                </MultiBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>