[英]How to use C# WPF ListView with variable number of columns
我想從外部各種來源(例如文本文件,csv文件,用戶輸入等)加載一些數據,並使用C#WPF在列表視圖中顯示。 我只需要一次顯示一個來源,並且一個來源內的列數是固定的,但是不同的來源可能包含不同的列數,例如,
File1可能具有以下列:名稱,編號,Cat1,Cat2,Cat3
File2可能具有以下列:名稱,編號,CatA,CatB
File3可能具有以下列:名稱,索引,Type1,...,TypeN
...
似乎C#WPF中的listview只能與已知數量的列一起使用,是否可以使用與上述數據類似的,僅在RUNTIME中已知列數的listview? 還是我應該使用其他方法,我還不知道。 謝謝。
要將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;
}
}
用戶界面示例:
<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>
以及后面的正確代碼:
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;
}
}
}
經過數據測試:
Name;Number;Cat1;Cat2;Cat3
someName;someNumber;someCat1;someCat2;someCat3
someOtherName;someOtherNumber;someOtherCat1;someOtherCat2;someOtherCat3
看起來像:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.