简体   繁体   English

如何自动将字符串数组绑定到 WPF DataGrid?

[英]How do I automatically bind a string array to a WPF DataGrid?

I have a DataGrid inside of a UserControl .我在UserControl有一个DataGrid 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>

I have the UserControl in my MainWindow that looks like this:我的MainWindow中有UserControl ,如下所示:

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

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

In my code behind I just set ItemsSource equal to the array of arrays as shown below:在我后面的代码中,我只是将ItemsSource设置为等于数组的数组,如下所示:

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

        }
    }
}

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.我认为使用DataGrid您可以将string[][]List<string[]>类的内容绑定到ItemsSource ,它只会生成列。 It is currently automatically generating columns, it just isn't filling them with the contents of the string[][] .它目前正在自动生成列,只是没有用string[][]的内容填充它们。

DataGrid 's auto-generate columns feature isn't quite suitable for displaying jagged array data. DataGrid的自动生成列功能不太适合显示锯齿状数组数据。 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.它更适用于单维集合,其中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).除非ItemsSource的项目是准备好显示的模型,否则您不应依赖自动生成列功能(它将显示所有属性的列,包括那些不打算显示的属性)。 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没有关于它应该如何命名列的信息。

In the end, I think you better define DataGrid columns somehow, instead of letting DataGrid it self generate the columns.最后,我认为您最好以某种方式定义DataGrid列,而不是让DataGrid自行生成列。 Either define it from XAML, for example, assuming you always have two "columns" in the array :例如,从 XAML 定义它,假设数组中总是有两个“列”:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM