具有动态定义的 WPF GridView [英] WPF GridView with a dynamic definition

查看:30
本文介绍了具有动态定义的 WPF GridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use the GridView mode of a ListView to display a set of data that my program will be receiving from an external source. The data will consist of two arrays, one of column names and one of strings values to populate the control.

我不知道如何创建一个合适的类,我可以将其用作 ListView 中的 Item.我知道填充 Items 的唯一方法是将其设置为具有代表列的属性的类,但在运行前我不知道这些列.

I don't see how to create a suitable class that I can use as the Item in a ListView. The only way I know to populate the Items is to set it to a class with properties that represent the columns, but I have no knowledge of the columns before run-time.

我可以按照以下说明动态创建 ItemTemplate:在运行时动态创建 WPF ItemTemplate 但它仍然让我不知道如何描述实际数据.

I could create an ItemTemplate dynamically as described in: Create WPF ItemTemplate DYNAMICALLY at runtime but it still leaves me at a loss as to how to describe the actual data.

感谢收到任何帮助.

推荐答案

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

You can add GridViewColumns to the GridView dynamically given the first array using a method like this:

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 来拆分数组.原理演示如下:

I assume the second array containing the values will be of ROWS * COLUMNS length. In that case, your items can be string arrays of length COLUMNS. You can use Array.Copy or LINQ to split up the array. The principle is demonstrated here:

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

这篇关于具有动态定义的 WPF GridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆