2

我有一个列表视图,它有一个额外的属性,我用它来为列表视图创建动态列

我有一个列表视图,它有一个额外的属性,我用它来为列表视图创建动态列

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 绑定,后者由 CountItem 的 ObserverableCollection 组成。CountItem 是一个简单的类,包含一个 Date 和另一个 ObserverableCollection 的 SubItems,然后包含 Firstname、Lastname 和 Account number。

在我的代码中,第一列必须是日期(正确绑定),但以下列是带有子项的 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");
                });
        }
4

1 回答 1

1

要绑定到子项,只需像这样设置绑定的路径属性:

{Binding Item, Path=SubItem1}
于 2012-09-10T19:36:18.857 回答