WPF Combobox DisplayMemberPath

Viewed 99318

Ok, I looked at other questions and didn't seem to get my answer so hopefully someone here can.

Very simple question why does the DisplayMemberPath property not bind to the item?

<ComboBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding PromptList}" DisplayMemberPath="{Binding Name}" SelectedItem="{Binding Prompt}"/>

The trace output shows that it is trying to bind to the class holding the IEnumerable not the actual item in the IEnumerable. I'm confused as to a simple way to fill a combobox without adding a bunch a lines in xaml.

It simply calls the ToString() for the object in itemssource. I have a work around which is this:

<ComboBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding PromptList}"  SelectedItem="{Binding Prompt}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

But in my opinion it's too much for such a simple task. Can I use a relativesource binding?

7 Answers

Trying this :

<ComboBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding PromptList}"  SelectedItem="{Binding Prompt}">
<ComboBox.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding Content}"/>
    </DataTemplate>
</ComboBox.ItemTemplate>

from what i can figure,

"DisplayMemberPath" uses reflection to get the property name in the data context class, if it cant find it nothing will be displayed.

if class

class some_class{
  string xxx{ get; }
}

DisplayMemberPath=xxx, will show whatever value "xxx" is

if you want to concatenate properties from the datacontext you need to create an item template, which will show up in the header and the drop down list.

<ComboBox.ItemTemplate>
          <DataTemplate DataType="employee">
            <StackPanel Orientation="Horizontal">
              <TextBlock Text="{Binding first_name}" />
              <TextBlock Text="" />
              <TextBlock Text="{Binding last_name}" />
            </StackPanel>
          </DataTemplate>
        </ComboBox.ItemTemplate>

you cannot have "DisplayMemberPath" and "ComboBox.ItemTemplate" set at the same time.

Related