How do I bind a WPF ComboBox to a List<Objects> in XAML?
Solution 1
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
Solution 2
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; }
will work but public long UserCode;
wont
JohnB
Seasoned software professional looking for new challenging oppportunities.
Updated on August 03, 2022Comments
-
JohnB over 1 year
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
-
JohnB about 7 yearsThanks NR: I wasn't setting my DataContext in my constructor. Works fine now.
-
Noah Reinagel about 7 yearsI'm glad to hear it!