user1095549
user1095549

Reputation: 1419

two filed in a wpf comboBox

I fill my ComboBox like this

            using (MorEntities1 c = new MorEntities1())
        {
            var myViewSource = new CollectionViewSource { Source = c.People.ToList() };
            myViewSource.SortDescriptions.Add(
              new SortDescription("Family_Name", ListSortDirection.Ascending)
            );
            CB_Coehn.ItemsSource = myViewSource.View;
            CB_Coehn.DisplayMemberPath = "Family_Name";
            CB_Coehn.SelectedValuePath = "Person_Id";
            CB_Coehn.SelectedIndex = 0;
       } 

But in the database I have a field First Name and field Last Name , How can I view the two fields in the ComboBox (LastName , FirstName) ?

This is in WPF and c#

Thanks in advance for help

Upvotes: 1

Views: 429

Answers (2)

Thelonias
Thelonias

Reputation: 2935

If you have control over the "People" class, you could create a new property called "DisplayName" that formats it the way you want and set your DisplayMemberPath to that property:

public string DisplayName
{
    get { return string.format("{0}, {1}", LastName, FirstName); }
}

CB_Coehn.DisplayMemberPath = "DisplayName";

If you can do all of this in XAML instead of the code-behind, you can do it like this:

<ComboBox x:Name="CB_Coehn">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding StringFormat="{0}, {1}">
                            <Binding Path="LastName" />
                            <Binding Path="FirstName" />
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>
            </Grid>
        </DataTemplate>
    </ComboBox.ItemTemplate>

Note: I have NOT tested this code, only going by memory, but it should be at least very close.

Upvotes: 2

N_A
N_A

Reputation: 19897

You need to create an itemscontrol itemtemplate which contains two labels and then bind their Text properties to the item.firstName and item.lastName.

See here for an example.

Upvotes: 1

Related Questions