Introduction to Silverlight > Using Templates > Data Templates > Populate the Controls |
Before we start using templates and styles, let us populate the controls first. To do that, complete the following:
C# |
Copy Code
|
---|---|
public Page() { InitializeComponent(); // Get list of items IEnumerable list = GetItems(); // Add items to ListBox and in C1ComboBox _listBox.ItemsSource = list; _cmb1.ItemsSource = list; // Show fonts in the other C1ComboBox FontFamily[] ff = new FontFamily[] { new FontFamily("Default font"), new FontFamily("Arial"), new FontFamily("Courier New"), new FontFamily("Times New Roman"), new FontFamily("Trebuchet MS"), new FontFamily("Verdana") }; _cmb2.ItemsSource = ff; } |
The code populates the ListBox and both C1ComboBoxes by setting their ItemsSource property. ItemsSource is a standard property present in most controls that support lists of items (ListBox, DataGrid, C1ComboBox, and so on).
C# |
Copy Code
|
---|---|
List<DataItem> GetItems() { List<DataItem> members = new List<DataItem>(); foreach (MemberInfo mi in this.GetType().GetMembers()) { members.Add(new DataItem(mi)); } return members; } |
C# |
Copy Code
|
---|---|
public class DataItem { public string ItemName { get; set; } public MemberTypes ItemType { get; set; } public DataItem(MemberInfo mi) { ItemName = mi.Name; ItemType = mi.MemberType; } } |
If you run the project now, you will see that the controls are being populated. However, they don't do a very good job of showing the items:
The controls simply convert the DataItem objects into strings using their ToString() method, which we didn't override and by default returns a string representation of the object type ("Templates.DataItem").
The bottom C1ComboBox displays the font family names correctly. That's because the FontFamily class implements the ToString() method and returns the font family name.
It is easy to provide a ToString() implementation that would return a more useful string, containing one or more properties. For example:
C# |
Copy Code
|
---|---|
public override string ToString() { return string.Format("{0} {1}", ItemType, ItemName); } |
If you add this method to the DataItem class and run the project again, you will see a slightly more satisfying result. But there's only so much you can do with plain strings. To represent complex objects effectively, we need something more. Enter Data Templates!