简体   繁体   中英

C# WPF Combobox with List<class>

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
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM