如何自动将字符串数组绑定到WPF DataGrid? [英] How do I automatically bind a string array to a WPF DataGrid?

查看:89
本文介绍了如何自动将字符串数组绑定到WPF DataGrid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UserControl内有一个DataGrid.看起来像这样:

I have a DataGrid inside of a UserControl. It looks like this:

<UserControl x:Class="ExternalDataSourceComparison.ImportedInfoGrid"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300"
         Height="Auto" Width="Auto">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <DataGrid Name="_dataGrid" Grid.Row="0">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path[0].Length}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

我的MainWindow中有一个UserControl,看起来像这样:

I have the UserControl in my MainWindow that looks like this:

<Window x:Class="ExternalDataSourceComparison.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ExternalDataSourceComparison"
    Title="MainWindow" Height="350" Width="525" WindowState="Maximized">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <local:ImportedInfoGrid x:Name="ExternalData" Grid.Row="0"/>
    <StackPanel Height="36px" Orientation="Horizontal" Grid.Row="1">
        <Button Name="_import" Content="Import Data" Margin="5" Padding="5, 2" Click="Import_Click"/>
        <Button Name="_compare" Content="Compare" Margin="5" Padding="5, 2" Click="Compare_Click"/>
        <Button Name="_cancel" Content="Cancel" Margin="5" Padding="5, 2" Click="Cancel_Click"/>            
    </StackPanel>
</Grid>

在我后面的代码中,使用方法fs.CSVToStringArray打开窗口,我打开一个CSV文件并将内容解析为string[][],外部数组代表行,内部数组代表所有列,因此是字符串[0] [3]将是第1行第4列.

In my code behind for the window using the method fs.CSVToStringArray, I open up a CSV file and parse out the contents to a string[][] the outer array represents the rows and the inner array are all of the columns so string[0][3] would be row 1 column 4.

在后面的代码中,我将ItemsSource设置为等于数组的数组,如下所示:

In my code behind I just set ItemsSource equal to the array of arrays as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;

namespace ExternalDataSourceComparison
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        FileStuff fs = new FileStuff();
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Import_Click(object sender, RoutedEventArgs e)
        {
            string[][] array = fs.CSVToStringArray();
            this.ExternalData._dataGrid.ItemsSource = array;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Compare_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}

输出不是我所期望的.我认为它显示的是对象的属性,而不是实际的内容.有没有一种方法可以自动生成行和列,还是我必须编写代码来创建列和构建行?我认为使用DataGrid可以将string[][]List<string[]>之类的东西绑定到ItemsSource,它只会生成列.它当前正在自动生成列,只是没有用string[][]的内容填充它们.

The output is not what I expected at all though. I think it showing the attributes of the object instead of the actual content. Is there a way to automatically generate rows and columns or will I have to write the code to create the columns and build the rows? I thought with a DataGrid you could bind something like a string[][] or a List<string[]> to the ItemsSource and it would just generated columns. It is currently automatically generating columns, it just isn't filling them with the contents of the string[][].

推荐答案

DataGrid的自动生成列功能不适用于显示锯齿状数组数据.它更适合于单个一维集合,其中DataGrid中的每一行代表集合中的单个项目,而每一列代表相应项目的不同属性.

DataGrid's auto-generate columns feature isn't quite suitable for displaying jagged array data. It is better suited for single, one-dimentional collection where each row in DataGrid represent single item in collection, and each column represent different property of corresponding item.

并且除非ItemsSource中的项目是可以显示的模型,否则您不应该依赖自动生成列功能(它将为所有属性显示列,包括那些不打算显示的属性).尝试自动DataGrid绑定到数组时的另一个问题是,DataGrid没有有关如何命名列的信息.

And unless the item in ItemsSource is a model that is ready for display, you shouldn't rely on auto-generate columns feature (it will display column for all properties, including those properties not meant to be displayed). Another issue when trying to automagically bind DataGrid to array is, DataGrid doesn't have information on how it should name the column.

最后,我认为您最好以某种方式定义DataGrid列,而不是让DataGrid自行生成列.例如,假设您在数组中始终有两个列",则可以从XAML定义它:

In the end, I think you better define DataGrid columns somehow, instead of letting DataGrid it self generate the columns. Either define it from XAML, for example, assuming you always have two "columns" in the array :

<DataGrid Name="_dataGrid" Grid.Row="0" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Column 1" Binding="{Binding [0]}"/>
        <DataGridTextColumn Header="Column 2" Binding="{Binding [1]}"/>
    </DataGrid.Columns>
</DataGrid>

或者,如果您具有动态的列数,则可以从代码中定义列,例如:

Or define the columns from code, in case you have dynamic number of columns, for example :

string[][] array = fs.CSVToStringArray();
for (int i = 0; i < array[0].Length; i++)
{
    var col = new DataGridTextColumn();
    col.Header = "Column " + i;
    col.Binding = new Binding(string.Format("[{0}]", i));
    _dataGrid.Columns.Add(col);
}
this.ExternalData._dataGrid.ItemsSource = array;

这篇关于如何自动将字符串数组绑定到WPF DataGrid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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