WPF GridView具有动态定义

时间:2008-12-10 14:05:51

标签: wpf gridview listview

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

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

我可以动态创建一个ItemTemplate,如下所述:Create WPF ItemTemplate DYNAMICALLY at runtime但是它仍然让我不知道如何描述实际数据。

感激不尽的任何帮助。

6 个答案:

答案 0 :(得分:11)

您可以使用如下方法在给定第一个数组的情况下动态地将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>

答案 1 :(得分:5)

谢谢,这非常有帮助。

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

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

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

答案 2 :(得分:4)

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

答案 3 :(得分:3)

不确定它是否仍然相关但我找到了一种使用celltemplate选择器设置单个单元格样式的方法。这有点hacky,因为你必须使用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,以便行是字典(ColumnName - &gt; Cell Object)。

我不能保证这个解决方案不会破坏或将来不会破坏.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/

答案 4 :(得分: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++;
        }

答案 5 :(得分:1)

我会通过向GridView添加AttachedProperty来实现这一点,我的MVVM应用程序可以在其中指定列(可能还有一些额外的元数据)。然后,行为代码可以直接使用GridView对象动态地创建列。通过这种方式,您可以遵守MVVM,ViewModel可以动态指定列。

豫ICP备18024241号-1