简体   繁体   中英

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:

<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

current output:

很白

You don't set DataContext anywhere

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 . Same as the name of property, not the type of item

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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