Home > front end >  C# WPF Combobox with List<class>
C# WPF Combobox with List<class>

Time:04-27

I have a C# WPF application. In my XAML for the view I have a combobox (x:Name="cboCities") and I use code behind to work with it.

I want to add some items (Cityname and ZIP) to this combobox. These items are in a List>clsCity>

I want to display the Cityname in the Comboxbox but instead I get something like "clsCity" shown.

I think that I need to set DisplayMemberPath correcly, but I dont know how.

This is what I have :

public class clsCity
{
    public int ZIP { get; set; }
    public string Cityname { get; set; }

    public clsCity(int zip, string cityname)
    {
        ZIP = zip;
        Cityname = cityname;
    }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<clsCity> Cities = new List<clsCity>();

        Cities.Add(new clsCity(12345, "London"));
        Cities.Add(new clsCity(67890, "Berlin"));
        Cities.Add(new clsCity(11223, "New York"));

        cboCities.ItemsSource = Cities;
        
        cboCities.DisplayMemberPath = ???  //Display Cityname in Comboxbox
    }

CodePudding user response:

If you want to set the DisplayMemberPath in code-behind, simply write:

cboCities.DisplayMemberPath = "Cityname";

If you want to set it in xaml, write:

<ComboBox Name="cboCities" ItemsSource="{Binding Path=Cities}" DisplayMemberPath="Cityname" />

(assuming that the DataContext has been set)

CodePudding user response:

Try to set cboCities.DisplayMemberPath = nameof(clsCity.Cityname)

nameof doc

A nameof expression produces the name of a variable, type, or member as the string constant

DisplayMemberPath doc

The path to a value on the source object. This can be any path, or an XPath such as "@Name". The default is an empty string ("").

If DisplayMemberPath is not specified and there is no DataTemplate, then the ListBox (in your case Combobox) displays a string representation of each object in the underlying collection.

  • Related