In order to bind the VIBlend DataGrid to indexed properties, you need to do the following:
1. Create DataTemplates that are bound to indexed properties.
<DataTemplate x:Key="LastNameCellTemplate">
<Grid>
<TextBlock Text="{Binding [LastName], Mode=OneWay}"/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="FirstNameCellTemplate">
<Grid>
<TextBlock Text="{Binding [FirstName], Mode=OneWay}"/>
</Grid>
</DataTemplate>
2. Create a new DataGrid instance. Set the CellDataTemplate property of the DataGrid’s BoundFields to point to the DataTemplates.
<viblend:DataGrid x:Name="dataGrid" Width="400" Height="280" AutoGenerateColumns="True">
<viblend:DataGrid.BoundFields>
<viblend:BoundField Text="FirstName" Width="150" CellDataTemplate="{StaticResource FirstNameCellTemplate}"/>
<viblend:BoundField Text="LastName" Width="150" CellDataTemplate="{StaticResource LastNameCellTemplate}"/>
</viblend:DataGrid.BoundFields>
</viblend:DataGrid>
3. Create a new class that will represent a single record of the DataGrid.
CSharp
public class Person : INotifyPropertyChanged
{
public Person()
{
}
private Dictionary<string, object> data = new Dictionary<string, object>();
public object this[string key]
{
get
{
if (!data.ContainsKey(key))
{
data[key] = null;
}
return data[key];
}
set
{
data[key] = value;
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(""));
}
}
}
public IEnumerable<string> Keys
{
get
{
return data.Keys;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
VB .NET
Public Class Person
Implements INotifyPropertyChanged
Public Sub New()
End Sub
Private data As Dictionary(Of String, Object) = New Dictionary(Of String, Object)()
Default Public Property Item(ByVal key As String) As Object
Get
If (Not data.ContainsKey(key)) Then
data(key) = Nothing
End If
Return data(key)
End Get
Set(ByVal value As Object)
data(key) = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(""))
End Set
End Property
Public ReadOnly Property Keys() As IEnumerable(Of String)
Get
Return data.Keys
End Get
End Property
Public Event PropertyChanged As PropertyChangedEventHandler
End Class
4. Create a new generic List of Person objects and set the ItemsSource property of the DataGrid, in order to bind it to the list.
CSharp
List<Person> listOfPersons = new List<Person>();
for (int i = 0; i < 10; i++)
{
Person person = new Person();
person["FirstName"] = "FirstName" + i;
person["LastName"] = "LastName" + i;
listOfPersons.Add(person);
}
this.dataGrid.ItemsSource = listOfPersons;
VB .NET
Dim listOfPersons As List(Of Person) = New List(Of Person)()
For i As Integer = 0 To 9
Dim person As New Person()
person("FirstName") = "FirstName" & i
person("LastName") = "LastName" & i
listOfPersons.Add(person)
Next i
Me.dataGrid.ItemsSource = listOfPersons