带列表的 C# WPF 组合框<class>
C# WPF Combobox with List<class>
我有一个 C# WPF 应用程序。
在我的 XAML 视图中,我有一个组合框 (x:Name="cboCities"),我使用代码隐藏来处理它。
我想向此组合框中添加一些项目(城市名称和邮政编码)。
这些项目在 List>clsCity>
我想在 Comboxbox 中显示城市名称,但我却显示了类似“clsCity”的内容。
我认为我需要正确设置 DisplayMemberPath,但我不知道如何设置。
这就是我的:
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
}
尝试设置
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.
我有一个 C# WPF 应用程序。 在我的 XAML 视图中,我有一个组合框 (x:Name="cboCities"),我使用代码隐藏来处理它。
我想向此组合框中添加一些项目(城市名称和邮政编码)。 这些项目在 List>clsCity>
我想在 Comboxbox 中显示城市名称,但我却显示了类似“clsCity”的内容。
我认为我需要正确设置 DisplayMemberPath,但我不知道如何设置。
这就是我的:
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
}
尝试设置
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.