0

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.

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Can I alter DisplayMemberPath on the fly to have an index associated with it as well?
@JW - do you want to display the index as well? You're question wasn't clear on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.