Altough the use of the ItemSource
is perfectly valid. I suggest you work with Data Binding
. Here's a nice definition from MSDN:
Data binding is the process that establishes a connection between the application UI and business logic. If the binding has the correct settings and the data provides the proper notifications, then, when the data changes its value, the elements that are bound to the data reflect changes automatically. Data binding can also mean that if an outer representation of the data in an element changes, then the underlying data can be automatically updated to reflect the change. For example, if the user edits the value in a TextBox element, the underlying data value is automatically updated to reflect that change.
I have answered a question where someone also had a problem with binding items to a ListBox. This is not a ComboBox but the principle is the same. Click here to go the question, and here to go straight to the answer.
Basically it comes down to this:
- Set up your UI
- Bind your data
In following code, I changed the properties a bit according to the properties used in the tutorial.
XAML:
<ListBox Margin="20" ItemsSource="{Binding Products}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=ProductId}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public class ProductViewModel
{
public List<Product> Products
{
get
{
return new List<Product>
{
new Product{ ProductId = 1, Name = "Product_1" },
new Product{ ProductId = 2, Name = "Product_2" }
};
}
}
}
//Following code can be placed in the Loaded event of the page:
DataContext = new ProductViewModel();