WPF ComboBox 与对象的绑定问题
WPF ComboBox binding issue with objects
我读过几个样本,例如:
- wpf combobox binding
- WPF: How to bind object to ComboBox
但今天是星期五,我的眼睛似乎是方形的。我看不出我的错误:
public ObservableCollection<Customer> Customers { get; private set; }
public MainWindow()
{
InitializeComponent();
this.Customers = new ObservableCollection<Customer>();
this.Customers.Add(new Customer() { ID = 123, Name = "John Doe" });
this.Customers.Add(new Customer() { ID = 456, Name = "Doe John" });
}
和我的 XAML:
<ComboBox x:Name="cbCustomer"
ItemsSource="{Binding Customer}"
DisplayMemberPath="Name"
SelectedValuePath="ID">
</ComboBox>
我了解到您可以使用数据模板或上面的代码。我更喜欢简单的下拉菜单,就像在网络表单中一样:<asp:dropdownlist etc>
只有在 WPF
中
当前输出:
你没有在任何地方设置DataContext
InitializeComponent();
this.Customers = new ObservableCollection<Customer>();
this.DataContext = this;
this.Customers.Add(new Customer() { ID = 123, Name = "John Doe" });
this.Customers.Add(new Customer() { ID = 456, Name = "Doe John" });
和 ItemsSource
应该是 Customers
,而不是 Customer
。与 属性 的名称相同,而不是项目的类型
<ComboBox ... ItemsSource="{Binding Customers}">
我读过几个样本,例如:
- wpf combobox binding
- WPF: How to bind object to ComboBox
但今天是星期五,我的眼睛似乎是方形的。我看不出我的错误:
public ObservableCollection<Customer> Customers { get; private set; }
public MainWindow()
{
InitializeComponent();
this.Customers = new ObservableCollection<Customer>();
this.Customers.Add(new Customer() { ID = 123, Name = "John Doe" });
this.Customers.Add(new Customer() { ID = 456, Name = "Doe John" });
}
和我的 XAML:
<ComboBox x:Name="cbCustomer"
ItemsSource="{Binding Customer}"
DisplayMemberPath="Name"
SelectedValuePath="ID">
</ComboBox>
我了解到您可以使用数据模板或上面的代码。我更喜欢简单的下拉菜单,就像在网络表单中一样:<asp:dropdownlist etc>
只有在 WPF
当前输出:
你没有在任何地方设置DataContext
InitializeComponent();
this.Customers = new ObservableCollection<Customer>();
this.DataContext = this;
this.Customers.Add(new Customer() { ID = 123, Name = "John Doe" });
this.Customers.Add(new Customer() { ID = 456, Name = "Doe John" });
和 ItemsSource
应该是 Customers
,而不是 Customer
。与 属性 的名称相同,而不是项目的类型
<ComboBox ... ItemsSource="{Binding Customers}">