“Let's assume you wish to use DataBinding to manage a set of Person class instances.
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
public class Person
{
public Person (string name, int age)
{
this.Name = name;
this.Age = age;
}
private int mAge;
public int Age
{
get { return mAge; }
set { mAge = value; }
}
private string mName;
public string Name
{
get { return mName; }
set { mName = value; }
}
public override string ToString ()
{
return this.Name + " : " + this.Age.ToString();
}
Now we create a Persons class inheriting from generic ObservableCollection
public class Persons:ObservableCollection<Person>
{
public Persons ()
{
base.Add(new Person("Corrado",22));
base.Add(new Person("Giulia",1));
base.Add(new Person("Stefania",10));
}
}
We now use ObjectDataSource to create Persons instance and have it available as DataContext inside xaml.
<?Mapping XmlNamespace="tds" ClrNamespace="Demo" ?>
<Window x:Class="Demo.Window1"
xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005"
xmlns:tds="tds"
Title="Demo"
>
<Window.Resources>
<ObjectDataProvider x:Key="Persons" ObjectType="{x:Type tds:Persons}" />
<DataTemplate DataType="{x:Type tds:Person}">
<StackPanel Orientation="Horizontal">
<TextBlock Foreground="Red" Text="{Binding Name}" FontSize="14" />
<TextBlock Foreground="Blue" Text="{Binding Age}" FontSize="14"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource Persons}}" />
</Grid>
</Window>
Red lines are namespace to Xml mapping instructions (syntax is probably going to be modified on next CTP)
Magenta line is the ObjectDataProvider definition that allows us to use Person list as datasource on the listbox.
Green lines indicates that both ObjectDataProvider and DataTemplate objects are part of Windows Resources.
DataTemplate (in blue) describes how the UI should display the Person instance (otherwise the ToString() method it will be invoked) in this case I decided to use a StackPanel containing two textblocks both binding to Person properties.
Data are databound to listbox by ItemSource attribute (in orange)
Datatemplates are required because on WPF ItemsControls (like ListBox) are not limited to strings but can contain virtually everything.
Just a simpe demo, but as you know, we all need a starting point... :-)
”