Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 258
JohnB Avatar asked Feb 23 '17 17:02

JohnB


1 Answers

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

like image 105
Noah Reinagel Avatar answered Nov 10 '22 01:11

Noah Reinagel