0

A WPF ComboBox/ListBox itemtemplate/datatemplate question please.

Let's say that I set DisplayMember="Name", this is equivalent to

<DataTemplate>
   <TextBox Text="{Binding Name}" />
</DataTemplate>

"Name" is a field in my view model.

Now, if DisplayMember="{Binding Name}", "Name" is no longer a property in my view model but instead contains the name of the property in my view model that I want to display. Using an ItemTemplate, how would I set this up? Thank you in advance.

Seated
  • 31
  • 7

1 Answers1

0

DisplayMemberPath is a property of the ItemsControl. And its binding path will be resolved relative to the ItemsControl's DataContext, not its items.

Example (pseudo code without INPC interface implementation):

public class ViewModel
{
    // This sets the string name of the property (or the path to it)
    // to be displayed in the items.
    public string DisplayNameProperty {get; set;} = "Name" // Or = "Surname"

    // Items Source
    public IEnumerable Items {get; set;}
}
<ItemsControl ItemsSource="{Binding Items}"
              DisplayMemberPath="{Binding DisplayNameProperty}"/>

The binding in the DisplayMemberPath property will allow you to control from the ViewModel which property will be displayed in ItemsControl's items.

But in practice, such a task is extremely rare. Personally, in my practice, such a need has never arisen.

EldHasp
  • 6,079
  • 2
  • 9
  • 24
  • In a large financial application, I have probably 100 lists that need to be displayed in a combobox and I do not want to develop 100 different item templates. (Clemens response is for template selector.) I have a base class that manages all of this, and using DisplayMember="{Binding Name}" handled this nicely. I need to style the dropdown portion of a combobox, so I need to implement an item template with the same functionality that binding DisplayMember provided me. – Seated Oct 11 '22 at 15:04