WPF Databinding combobox to a list<string>
Solution 1
Posting my comment back to mark the answer.
My DataContext was set, BUT it was set after InitializeComponent(). I thought that could be the problem. Then I realized that as I am binding through xaml, when the view loads, the binding happens to the property which is empty.
The property gets populated when the view is ready after its loaded (i.e on _presenter.OnViewReady()). Since it's not an observable collection nothing gets added to the combobox. Specifying it from my code behind works, because at that time the data exists in the property.
Solution 2
Assume you have a List<Foo>
called Foos
in your window / page. Foo
has a property Name
. Now you set up the binding in XAML as follows:
<ComboBox ItemsSource="{Binding Path=Foos}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=Foo}"
/>
This is based on this SO question. Read this (WPF DataBinding overview) as a good foundation for databinding in WPF.
ioWint
Interested in creating software that helps people make an impact in changing the world. Amateur photographer, foodie and world traveler. -ioWint
Updated on July 12, 2022Comments
-
ioWint almost 2 years
I am having a difficult time trying to bind my property which is of type List to my combobox through XAML.
public List<string> MyProperty { get; set; }
The following XAML binding does not work:
<ComboBox Name="cboDomainNames" ItemsSource="{Binding Path=MyProperty}"/>
But the following assignment:
cboDomainNames.ItemsSource = MyProperty;
works perfectly. What i am missing here?
-
ioWint almost 13 yearsTrue, but presently i am interested with a property of List<string>! if code behind assignment of ItemsSource hasnt worked then i wouldnt be more confused! would have gone with a custom entity thinking i always need the DisplayMemberPath!
-
ioWint almost 13 yearsi tried this Mario! but hard luck! i couldnt get it populated. view is inheriting from a baseView, so instead of window i put my baseView! it still doesnt get binded!
-
JWP over 9 yearsWasn't a solution to binding to a List<string>