如何自动将字符串数组绑定到WPF DataGrid?
我在UserControl
有一个DataGrid
。 它看起来像这样:
我在MainWindow
中有UserControl
,如下所示:
在使用方法fs.CSVToStringArray
的窗口后面的代码中,我打开一个CSV文件并将内容解析为string[][]
外部数组表示行,内部数组是所有列,因此字符串[ 0] [3]将是第1行第4列。
在我的代码后面我只是将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 { /// /// Interaction logic for MainWindow.xaml /// 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[][]
的内容填充它们。
DataGrid
的自动生成列function不太适合显示锯齿状arrays数据。 它更适合单个,一维集合,其中DataGrid
中的每一行代表集合中的单个项目,每列代表相应项目的不同属性。
除非ItemsSource
的项目是可以显示的模型,否则您不应该依赖自动生成列function(它将显示所有属性的列,包括那些不打算显示的属性)。 尝试自动将DataGrid
绑定到数组时的另一个问题是, DataGrid
没有关于如何命名列的信息。
最后,我认为你最好以某种方式定义DataGrid
列,而不是让DataGrid
自己生成列。 例如,假设您在数组中始终有两个“列”,则可以从XAML定义它:
或者从代码中定义列,以防您有动态列数,例如:
上述就是C#学习教程:如何自动将字符串数组绑定到WPF DataGrid?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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;
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1011882.html