I have a listview which has an extra property which I use to create dynamic columns to a Listview
I have a listview which has an extra property which I use to create dynamic columns to a Listview
public class ListViewExtension
{
public static readonly DependencyProperty MatrixSourceProperty = DependencyProperty.RegisterAttached("MatrixSource", typeof(ObservableCollection<CountItem>), typeof(ListViewExtension), new FrameworkPropertyMetadata(null, OnMatrixSourceChanged));
public static IEnumerable<CountItem> GetMatrixSource(DependencyObject d)
{
return (ObservableCollection<CountItem>)d.GetValue(MatrixSourceProperty);
}
public static void SetMatrixSource(DependencyObject d, ObservableCollection<CountItem> value)
{
d.SetValue(MatrixSourceProperty, value);
}
private static void OnMatrixSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ListView listView = (ListView)d;
ObservableCollection<CountItem> items = (ObservableCollection<CountItem>)e.NewValue;
listView.ItemsSource = items;
GridView gridView = new GridView();
foreach (CountItem countItem in items)
{
gridView.Columns.Add(
new GridViewColumn
{
Header = "Date",
DisplayMemberBinding = new Binding("Date")
});
foreach (SubItem subItem in countItem.SubItems)
{
gridView.Columns.Add(
new GridViewColumn
{
Header = String.Format("{0} {1}", subItem.Firstname, subItem.Lastname),
DisplayMemberBinding = new Binding("AccountNumber")
});
}
}
listView.View = gridView;
}
}
<ListView MoneyCounter:ListViewExtension.MatrixSource="{Binding CountItems}" />
The list is bound with CountItems, which consists of a ObserverableCollection of CountItem. CountItem is a simple class with a Date and another ObserverableCollection of SubItems, which then contains Firstname, Lastname and Account number.
In my code the first column must be the Date (which binds correctly), but then the following columns are N columns with SubItems.
But how do I bind these items?
Answer:
After some fiddeling I got to:
for (Int32 i = 0; i < countItem.SubItem.Count; i++)
{
SubItem subItem = countItem.DenominationItems[i];
gridView.Columns.Add(
new GridViewColumn
{
Header = String.Format("{0} {1}", subItem.Firstname, subItem.Lastname),
DisplayMemberBinding = new Binding("SubItems["+i+"].AccountNumber");
});
}
To bind to subitems simply set the path property of a binding like this: