Reputation: 70
I want a whole lot of items from a list to appear in a comboBox. I'm relatively new at c# and thus not sure of all the functions i can perform on "stuff". For example, I have a simple class:
puclic Class Foo
{
public String s;
public Foo(String _s)
{s = _s;}
}
I then have a combo box and a list of Foo's:
List<Foo> luFoo = new List<Foo>();
//add a bunch of Foo's to luFoo
I then wish for the various items in luFoo to appear in comboBox. I've gotten as far as the following code from various posts, but the rest seem kind of vague or I can't find the properties of the comboBox they used.
cmbFoo.ItemsSource = luFoo;
Any help whatsoever would be largely appreciated, Thank you.
Edit:
Foo a = new Foo("a");
Foo b = new Foo("b");
Foo c = new Foo("c");
Foo d = new Foo("d");
Foo e = new Foo("e");
luFoo.Add(a);
luFoo.Add(b);
luFoo.Add(c);
luFoo.Add(d);
luFoo.Add(e);
the code where i create and add Foo's to luFoo
Upvotes: 1
Views: 223
Reputation: 66509
It looks like your almost there. I imagine at this point, the only thing in your ComboBox are strange-looking strings, which are actually the full namespace of the Foo
class.
What you have to do next is set the property that will be displayed to the user in the ComboBox:
cmbFoo.ItemsSource = luFoo;
cmbFoo.DisplayMemberPath = "s";
Note that if you were using the MVVM pattern, you would do something like this in your XAML to achieve a similar result, but if you're relatively new you probably haven't learned this yet.
<ComboBox ItemsSource="{Binding Path=luFoo}" DisplayMemberPath="s" />
Beyond that, the documentation is always a great resource for learning about the different methods, events and properties available for a control.
As Flat Eric noted, you'd have to modify your class as well. After converting s
to a property, adding items to your list, and setting the DisplayMemberPath
, you should see the various values of s
listed in your ComboBox.
public class Foo
{
public String s { get; set; }
public Foo(String _s)
{
s = _s;
}
}
Upvotes: 3