简体   繁体   中英

How do I bind a WPF ComboBox to a List<Objects> in XAML?

I'm having issues binding a WPF ComboBox in XAML.

Here is my object definition and collection:

public class AccountManager
{
   public long UserCode { get; set; }
   public string UserName { get; set; }
}

public partial class MainWindow : Window
{    
   public List<AccountManager> AccountManagers;
}

Here is the XAML definition of my ComboBox:

ComboBox Name="cbTestAccountManagers"
          ItemsSource="{Binding AccountManagers}"
          DisplayMemberPath="UserName"
          SelectedValuePath="UserCode"
          Width="250"

I'm not quite sure what I'm doing wrong here. I don't get any errors at run/load time. The ComboBox displays without any contents in the drop down. (It's empty).

Can someone point me in the right direction?

Thanks

your making a couple of mistakes

firstly you're not following MVVM

the correct MVVM should look as follows

public class AccountManager
{
   public long UserCode { get; set; }
   public string UserName { get; set; }
}
public class AccountManagersVM
{
   public ObservableCollection<AccountManager> AccountManagers{ get; set; }

}

then no need for changes to the code behind you just need to use the DataContext which can be set directly or via a binding

<Window.DataContext>
    <local:AccountManagersVM />
</Window.DataContext>
ComboBox ItemsSource="{Binding AccountManagers}"
          DisplayMemberPath="UserName"
          SelectedValuePath="UserCode"
          Width="250"

Second attributes/fields can't be bound only properties

eg public long UserCode { get; set; } public long UserCode { get; set; } public long UserCode { get; set; } will work but public long UserCode; wont

Your problem is simple. Change

public List<AccountManager> AccountManagers; 

to this

public List<AccountManager> AccountManagers { get; set; }

and make sure that you have these in your MainWindow constructor

public MainWindow()
{
    InitializeComponent();
    //Setup Account managers here
    DataContext = this;
}

you can only bind to properties not fields and you need to ensure the proper data context

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