到CSV轉換爲表(只是舉個例子,有做這個工作做得更好庫在那裏):
<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>
和背後的正確代碼:UI的
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;
}
}
例:
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
,看起來像:
使您的CSV的第一行包含列名? – 2015-02-23 07:08:23
我會使用一個數據網格而不是一個列表視圖。從csv數據(或類似的其他源類型)創建一個數據表,並將數據網格綁定到該數據表 – 2015-02-23 07:12:21