我是C#的新手, CSV数据无法在DataGrid的WPF UI上呈现,我从csv获取数据但无法在UI上显示,有人可以帮助我吗?
下面是我的 XAML 代码-
<Window x:Class="SampleApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SampleApp"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="825">
<DataGrid AutoGenerateColumns="True" Height="217" HorizontalAlignment="Left" Margin="73,33,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="707">
<DataGrid.Columns>
<DataGridTextColumn Header="Serials" Width="40" Binding="{Binding Serials}"></DataGridTextColumn>
<DataGridTextColumn Header="Number" Width="100" Binding="{Binding Number}"></DataGridTextColumn>
<DataGridTextColumn Header="InstalledCode" Width="100" Binding="{Binding InstalledCode}"></DataGridTextColumn>
<DataGridTextColumn Header="InstalledTime" Width="100" Binding="{Binding InstalledTime}"></DataGridTextColumn>
<DataGridTextColumn Header="Location" Width="100" Binding="{Binding Location}"></DataGridTextColumn>
<DataGridTextColumn Header="Site" Width="40" Binding="{Binding Site}"></DataGridTextColumn>
<DataGridTextColumn Header="UUID" Width="40" Binding="{Binding UUID}"></DataGridTextColumn>
<DataGridTextColumn Header="Uninstalled" Width="100" Binding="{Binding Uninstalled}"></DataGridTextColumn>
<DataGridTextColumn Header="Notes" Width="100" Binding="{Binding Notes}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Window>
更新1: 下面是 C# 代码:
private void LoadBound(string fName)
{
String textLine = string.Empty;
String[] splitLine;
var data = new DataTable();
var sharath = new DataTable();
data.Columns.AddRange(new[]
{
new DataColumn ("Serials"),
new DataColumn ("Number"),
new DataColumn ("InstalledCode"),
new DataColumn ("InstalledTime"),
new DataColumn ("Location"),
new DataColumn ("Site"),
new DataColumn ("UUID"),
new DataColumn ("Uninstalled"),
new DataColumn ("Notes")
});
data.Rows.Clear();
if (System.IO.File.Exists(fName))
{
System.IO.StreamReader objReader = new System.IO.StreamReader(fName);
var contents = objReader.ReadToEnd();
var strReader = new System.IO.StringReader(contents);
do
{
textLine = strReader.ReadLine();
if (textLine != string.Empty)
{
splitLine = textLine.Split(',');
if (splitLine[0] != string.Empty || splitLine[1] != string.Empty)
{
data.Rows.Add(splitLine[0]);
}
}
} while (strReader.Peek() != -1);
}
dataGrid1.DataContext = data;
}
更新2:
我的 csv 文件是
10,20,30,40,50,60,70,80
1,2,3,4,5,6,7,8
任何人都可以帮我将数据从 csv 填充到 WPF UI 吗?
你没有设置DataGrid.ItemsSource。
如果 DataContext 设置为 DataTable,则可以通过在 xaml 中的绑定来设置 ItemsSource:
ItemsSource="{Binding Path=DefaultView}"
或者设置项目从代码源:
dataGrid1.ItemsSource = data.DefaultView;