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

查看:83
本文介绍了如何自动将字符串数组绑定到 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[][]外部数组表示行,内部数组表示所有列,因此 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 之类的东西绑定到 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天全站免登陆