动态绑定列表集合到ListView

时间:2012-09-10 19:26:48

标签: wpf listview

我有一个listview,它有一个额外的属性,我用它来创建Listview的动态列

我有一个listview,它有一个额外的属性,我用它来创建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}" />

该列表与CountItems绑定,CountItems由CountItem的ObserverableCollection组成。 CountItem是一个简单的类,带有Date和另一个SubItems的ObserverableCollection,然后包含Firstname,Lastname和Account number。

在我的代码中,第一列必须是Date(正确绑定),但接下来的列是带有SubItems的N列。

但是如何绑定这些项?

答案: 经过一番戏弄后,我得到了:

        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");
                });
        }

1 个答案:

答案 0 :(得分:1)

要绑定到子项,只需设置绑定的path属性,如下所示:

{Binding Item, Path=SubItem1}