WPF ComboBox绑定问题与对象

时间:2015-04-17 14:30:25

标签: c# wpf data-binding

我已经阅读了几个样本:

但是星期五,我的眼睛看起来很方正。我无法看到自己的错误:

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>

我已经读过你可以使用datatemplate或上面的代码。我更喜欢简单的下拉菜单,就像在webforms中一样:<asp:dropdownlist etc>只有在WPF中

当前输出:

very white

1 个答案:

答案 0 :(得分:2)

您未将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 for应该是Customers,而不是Customer。与属性名称相同,而不是项目类型

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