13

我想使用 ListView 的 GridView 模式来显示我的程序将从外部源接收的一组数据。数据将包含两个数组,一个是列名,另一个是用于填充控件的字符串值。

我看不到如何创建可以用作 ListView 中的 Item 的合适类。我知道填充项目的唯一方法是将其设置为具有表示列的属性的类,但在运行时之前我不知道这些列。

我可以动态地创建一个 ItemTemplate,如:在运行时动态创建 WPF ItemTemplate但它仍然让我不知道如何描述实际数据。

感激地收到任何帮助。

4

6 回答 6

13

您可以使用以下方法将 GridViewColumns 添加到 GridView 动态给定第一个数组:

private void AddColumns(GridView gv, string[] columnNames)
{
    for (int i = 0; i < columnNames.Length; i++)
    {
        gv.Columns.Add(new GridViewColumn
        {
            Header = columnNames[i],
            DisplayMemberBinding = new Binding(String.Format("[{0}]", i))
        });
    }
}

我假设包含值的第二个数组将是 ROWS * COLUMNS 长度。在这种情况下,您的项目可以是长度为 COLUMNS 的字符串数组。您可以使用 Array.Copy 或 LINQ 来拆分数组。原理如下:

<Grid>
    <Grid.Resources>
        <x:Array x:Key="data" Type="{x:Type sys:String[]}">
            <x:Array Type="{x:Type sys:String}">
                <sys:String>a</sys:String>
                <sys:String>b</sys:String>
                <sys:String>c</sys:String>
            </x:Array>
            <x:Array Type="{x:Type sys:String}">
                <sys:String>do</sys:String>
                <sys:String>re</sys:String>
                <sys:String>mi</sys:String>
            </x:Array>
        </x:Array>
    </Grid.Resources>
    <ListView ItemsSource="{StaticResource data}">
        <ListView.View>
            <GridView>
                <GridViewColumn DisplayMemberBinding="{Binding Path=[0]}" Header="column1"/>
                <GridViewColumn DisplayMemberBinding="{Binding Path=[1]}" Header="column2"/>
                <GridViewColumn DisplayMemberBinding="{Binding Path=[2]}" Header="column3"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
于 2008-12-10T19:35:45.150 回答
6

谢谢,这很有帮助。

我用它来创建一个动态版本,如下所示。我按照您的建议创建了列标题:

private void AddColumns(List<String> myColumns)
{
    GridView viewLayout = new GridView();
    for (int i = 0; i < myColumns.Count; i++)
    {
        viewLayout.Columns.Add(new GridViewColumn
        {
            Header = myColumns[i],
            DisplayMemberBinding = new Binding(String.Format("[{0}]", i))
        });
    }
    myListview.View = viewLayout;
}

在 XAML 中非常简单地设置 ListView:

<ListView Name="myListview" DockPanel.Dock="Left"/>

为 ObservableCollection 创建了一个包装类来保存我的数据:

public class MyCollection : ObservableCollection<List<String>>
{
    public MyCollection()
        : base()
    {
    }
}

并将我的 ListView 绑定到它:

results = new MyCollection();

Binding binding = new Binding();
binding.Source = results;
myListview.SetBinding(ListView.ItemsSourceProperty, binding);

然后填充它,这只是清除所有旧数据并添加新数据的情况:

results.Clear();
List<String> details = new List<string>();
for (int ii=0; ii < externalDataCollection.Length; ii++)
{
    details.Add(externalDataCollection[ii]);
}
results.Add(details);

可能有更简洁的方法,但这对我的应用程序非常有用。再次感谢。

于 2008-12-18T19:56:47.650 回答
4

CodeProject 上的这篇文章准确解释了如何创建动态 ListView - 当数据仅在运行时已知时。 http://www.codeproject.com/KB/WPF/WPF_DynamicListView.aspx

于 2009-05-16T23:30:24.937 回答
3

不确定它是否仍然相关,但我找到了一种使用单元格模板选择器设置单个单元格样式的方法。这有点麻烦,因为您必须使用 ContentPresenter 的内容来获得单元格的正确 DataContext(因此您可以绑定到单元格模板中的实际单元格项):

    public class DataMatrixCellTemplateSelectorWrapper : DataTemplateSelector
    {
        private readonly DataTemplateSelector _ActualSelector;
        private readonly string _ColumnName;
        private Dictionary<string, object> _OriginalRow;

        public DataMatrixCellTemplateSelectorWrapper(DataTemplateSelector actualSelector, string columnName)
        {
            _ActualSelector = actualSelector;
            _ColumnName = columnName;
        }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            // The item is basically the Content of the ContentPresenter.
            // In the DataMatrix binding case that is the dictionary containing the cell objects.
            // In order to be able to select a template based on the actual cell object and also
            // be able to bind to that object within the template we need to set the DataContext
            // of the template to the actual cell object. However after the template is selected
            // the ContentPresenter will set the DataContext of the template to the presenters
            // content. 
            // So in order to achieve what we want, we remember the original DataContext and then
            // change the ContentPresenter content to the actual cell object.
            // Therefor we need to remember the orginal DataContext otherwise in subsequent calls
            // we would get the first cell object.

            // remember old data context
            if (item is Dictionary<string, object>)
            {
                _OriginalRow = item as Dictionary<string, object>;
            }

            if (_OriginalRow == null)
                return null;

            // get the actual cell object
            var obj = _OriginalRow[_ColumnName];

            // select the template based on the cell object
            var template = _ActualSelector.SelectTemplate(obj, container);

            // find the presenter and change the content to the cell object so that it will become
            // the data context of the template
            var presenter = WpfUtils.GetFirstParentForChild<ContentPresenter>(container);
            if (presenter != null)
            {
                presenter.Content = obj;
            }

            return template;
        }
    }

注意:我从 CodeProject 文章中更改了 DataMatrix,以便行是字典(列名 -> 单元格对象)。

我不能保证这个解决方案不会破坏某些东西,或者在未来的 .Net 版本中不会破坏。它依赖于 ContentPresenter 在将模板选择为它自己的内容后设置 DataContext 的事实。(反射器在这些情况下有很大帮助:))

创建 GridColumns 时,我会执行以下操作:

           var column = new GridViewColumn
                          {
                              Header = col.Name,
                              HeaderTemplate = gridView.ColumnHeaderTemplate
                          };
            if (listView.CellTemplateSelector != null)
            {
                column.CellTemplateSelector = new DataMatrixCellTemplateSelectorWrapper(listView.CellTemplateSelector, col.Name);
            }
            else
            {
                column.DisplayMemberBinding = new Binding(string.Format("[{0}]", col.Name));
            }
            gridView.Columns.Add(column);

注意:我扩展了 ListView 以便它具有可以在 xaml 中绑定的 CellTemplateSelector 属性

@Edit 15/03/2011:我写了一篇小文章,附有一个小演示项目:http: //codesilence.wordpress.com/2011/03/15/listview-with-dynamic-columns/

于 2010-06-30T23:37:32.910 回答
1

完全程序化的版本:

        var view = grid.View as GridView;
        view.Columns.Clear();
        int count=0;
        foreach (var column in ViewModel.GridData.Columns)
        {
            //Create Column
            var nc = new GridViewColumn();
            nc.Header = column.Field;
            nc.Width = column.Width;
            //Create template
            nc.CellTemplate = new DataTemplate();
            var factory = new FrameworkElementFactory(typeof(System.Windows.Controls.Border));
            var tbf = new FrameworkElementFactory(typeof(System.Windows.Controls.TextBlock));

            factory.AppendChild(tbf);
            factory.SetValue(System.Windows.Controls.Border.BorderThicknessProperty, new Thickness(0,0,1,1));
            factory.SetValue(System.Windows.Controls.Border.MarginProperty, new Thickness(-7,0,-7,0));
            factory.SetValue(System.Windows.Controls.Border.BorderBrushProperty, Brushes.LightGray);
            tbf.SetValue(System.Windows.Controls.TextBlock.MarginProperty, new Thickness(6,2,6,2));
            tbf.SetValue(System.Windows.Controls.TextBlock.HorizontalAlignmentProperty, column.Alignment);

            //Bind field
            tbf.SetBinding(System.Windows.Controls.TextBlock.TextProperty, new Binding(){Converter = new GridCellConverter(), ConverterParameter=column.BindingField});
            nc.CellTemplate.VisualTree = factory;

            view.Columns.Add(nc);
            count++;
        }
于 2011-08-04T11:01:07.953 回答
1

我将通过向 GridView 添加一个 AttachedProperty 来执行此操作,我的 MVVM 应用程序可以在其中指定列(可能还有一些额外的元数据)。然后行为代码可以直接与 GridView 对象动态工作以创建列。通过这种方式,您可以遵守 MVVM,并且 ViewModel 可以动态指定列。

于 2013-01-03T19:20:18.160 回答