简体   繁体   English

C# WPF Combobox 带列表<class></class>

[英]C# WPF Combobox with List<class>

I have a C# WPF application.我有一个 C# WPF 申请。 In my XAML for the view I have a combobox (x:Name="cboCities") and I use code behind to work with it.在我的 XAML 视图中,我有一个 combobox (x:Name="cboCities") 并且我使用代码隐藏来处理它。

I want to add some items (Cityname and ZIP) to this combobox. These items are in a List>clsCity>我想向这个 combobox 添加一些项目(Cityname 和 ZIP)。这些项目在 List>clsCity> 中

I want to display the Cityname in the Comboxbox but instead I get something like "clsCity" shown.我想在 Comboxbox 中显示城市名称,但我得到的是类似“clsCity”的显示。

I think that I need to set DisplayMemberPath correcly, but I dont know how.我认为我需要正确设置 DisplayMemberPath,但我不知道如何设置。

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 nameof 名称

A nameof expression produces the name of a variable, type, or member as the string constant nameof 表达式将变量、类型或成员的名称生成为字符串常量

DisplayMemberPath doc DisplayMemberPath 文档

The path to a value on the source object. This can be any path, or an XPath such as "@Name".源 object 上值的路径。这可以是任何路径,或 XPath,例如“@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.如果未指定 DisplayMemberPath 并且没有 DataTemplate,则 ListBox (in your case Combobox)显示基础集合中每个 object 的字符串表示形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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