简体   繁体   English

WPF与对象的组合框绑定问题

[英]WPF ComboBox binding issue with objects

I have read several samples like: 我已经阅读了几个示例,例如:

But it is friday and my eyes seem square. 但这是星期五,我的眼睛似乎很直。 I can't see my mistake: 我看不到我的错误:

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" });
}

and my XAML: 和我的XAML:

<ComboBox x:Name="cbCustomer" 
          ItemsSource="{Binding Customer}" 
          DisplayMemberPath="Name" 
          SelectedValuePath="ID">
</ComboBox>

I have read that you can either use a datatemplate or the code from above. 我已经读过您可以使用数据模板或上面的代码。 I prefer a simple dropdown, just like in webforms: <asp:dropdownlist etc> only then in WPF 我更喜欢简单的下拉菜单,就像在Webforms中一样: <asp:dropdownlist etc>仅在WPF中

current output: 当前输出:

很白

You don't set DataContext anywhere 您不会在任何地方设置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" });

and ItemsSource for should be Customers , not Customer . ItemsSource应为Customers ,而不是Customer Same as the name of property, not the type of item 与属性名称相同,而不是项目类型

<ComboBox ... ItemsSource="{Binding Customers}"> 

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

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