[英]How to use C# WPF ListView with variable number of columns
I would like to load some data from external various source such as text file, csv file, user input, etc, and display in a list view using C# WPF. 我想从外部各种来源(例如文本文件,csv文件,用户输入等)加载一些数据,并使用C#WPF在列表视图中显示。 I need to display one source at a time only, and the number of columns is fixed within one source, but different sources may contain different number of columns, eg,
我只需要一次显示一个来源,并且一个来源内的列数是固定的,但是不同的来源可能包含不同的列数,例如,
File1 may have following column: Name, Number, Cat1, Cat2, Cat3 File1可能具有以下列:名称,编号,Cat1,Cat2,Cat3
File2 may have following column: Name, Number, CatA, CatB File2可能具有以下列:名称,编号,CatA,CatB
File3 may have following column: Name, Index, Type1, ..., TypeN File3可能具有以下列:名称,索引,Type1,...,TypeN
... ...
Seems that the listview in C# WPF can only be used with a known number of columns, is it possible to use listview which the number of columns is only known in the RUNTIME, similar to the above data? 似乎C#WPF中的listview只能与已知数量的列一起使用,是否可以使用与上述数据类似的,仅在RUNTIME中已知列数的listview? or I should use a different approach, I have no idea yet.
还是我应该使用其他方法,我还不知道。 Thanks.
谢谢。
To convert csv to table (just an example, there are libraries out there that do this job better): 要将csv转换为表(仅作为示例,那里的库可以更好地完成此工作):
public static class ExtensionMethods
{
public static DataTable ConvertToDataTable(this string input)
{
DataTable result = new DataTable();
using (StringReader reader = new StringReader(input))
{
string[] columnNames = reader.ReadLine().Split(';'); //or other character
foreach (var columnName in columnNames)
{
result.Columns.Add(columnName, typeof(string));
}
while (reader.Peek() > 0)
{
result.Rows.Add(reader.ReadLine().Split(';'));
}
}
return result;
}
}
Example of the UI: 用户界面示例:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Name="btnLoad" Content="Load" Click="BtnLoad_OnClick"/>
<DataGrid Name="dgData" Grid.Row="1" ItemsSource="{Binding}"/>
</Grid>
</Window>
and the proper code behind: 以及后面的正确代码:
public partial class MainWindow : Window
{
private DataTable table;
public MainWindow()
{
InitializeComponent();
}
private void BtnLoad_OnClick(object senderIn, RoutedEventArgs eIn)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
string content = File.ReadAllText(dialog.FileName);
table = content.ConvertToDataTable();
dgData.DataContext = table;
}
}
}
Tested with data: 经过数据测试:
Name;Number;Cat1;Cat2;Cat3
someName;someNumber;someCat1;someCat2;someCat3
someOtherName;someOtherNumber;someOtherCat1;someOtherCat2;someOtherCat3
And looks like: 看起来像:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.