J W
J W

Reputation: 878

Changing the data for a ComboBox in WPF

So I have a ComboBox with data in it and it works how they want:

<ComboBox Grid.Column="1" x:Name="MyComboBox" Margin="2, 0, 2, 0" 
                          ItemsSource="{Binding Path=MySamples}" DisplayMemberPath="SampleName" SelectedValue="{Binding Path=MySample}" 
                          SelectionChanged="OnComboBoxChanged" FontSize="11" FontFamily="Arial"/>

However, now they want the ItemsSource to be indexed. So it should be something like:

some #: SampleName

Is there an easy way to make this change just for the ComboBox drop down without changing the architecture? I cannot change the List itself since in other areas of the map, it's just the SampleName without the index. Thanks.

Upvotes: 0

Views: 142

Answers (1)

ChrisF
ChrisF

Reputation: 137148

If your ItemsSource is a complex type:

public class MyClass
{
    public int Index { get; set; }
    public string Name { get; set; }
}

Then use the DisplayMemberPath property of the ComboBox to control what gets displayed. In this case you'd add:

DisplayMemberPath="SampleName"

to the ComboBox definition.

If instead you want to display both the index and name then you'll need to define an ItemTemplate for the ComboBox:

<ComboBox ....>
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Index}" />
        <TextBlock Text=" : " />
        <TextBlock Text="{Binding Name}" />
      </StackPanel>
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

Upvotes: 1

Related Questions