使用 UWP C# 在单独的行中显示文件行,在单独的列中显示每个单词 XAML

Displaying File lines in separate rows and each word on separate column using UWP C# XAML

我应该怎么做才能在 XAML 中的单独行中显示所有文件行?

我有这样的代码:

public async void ReadFile()
{

    var path = @"CPU.xls";
    var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

    var file = await folder.GetFileAsync(path);
    var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);

    foreach (string line in readFile.OrderBy(line =>
    {
        int lineNo;
        var success = int.TryParse(line.Split(';')[4], out lineNo);
        if (success) return lineNo;
        return int.MaxValue;
    }))
    {

        string[] splitLines = line.Split(';');

        ObservableCollection<ItemsData> items = new ObservableCollection<ItemsData>();
        for (int index = 0; index < splitLines.Length; index++)
        {
            ItemsData dataitem = new ItemsData
            {
                value0 = splitLines[0],
                value1 = splitLines[1],
                value2 = splitLines[2],
                value3 = splitLines[3],
                value4 = splitLines[4],
            };
            items.Add(dataitem);
        }
        itemsControl.DataContext = items;

    }

}

不幸的是,我没有在每个新行上获取每一行,而是在同一行上获取了五次。

我得到类似的东西:

John 24 IT
John 24 IT
John 24 IT

而不是得到:

John 24 IT
Mike 14 GB
Steve 22 RU

您将在每次出现循环时替换您的项目。

首先,在循环之外创建您的集合:

var items = new ObservableCollection<ItemsData>();

foreach (string line in readFile...

在循环内部,删除 for,因为您实际上并没有使用它:

string[] splitLines = line.Split(';');

ItemsData dataitem = new ItemsData
{
    value0 = splitLines[0],
    value1 = splitLines[1],
    value2 = splitLines[2],
    value3 = splitLines[3],
    value4 = splitLines[4],
};
items.Add(dataitem);

然后,当您退出 foreach 循环时,设置 DataContext:

itemsControl.DataContext = items;

最终代码如下所示:

public async void ReadFile()
{
    var path = @"CPU.xls";
    var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

    var file = await folder.GetFileAsync(path);
    var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);

    var items = new ObservableCollection<ItemsData>();

    foreach (string line in readFile.OrderBy(line =>
    {
        int lineNo;
        var success = int.TryParse(line.Split(';')[4], out lineNo);
        if (success) return lineNo;
        return int.MaxValue;
    }))
    {
        string[] splitLines = line.Split(';');

        ItemsData dataitem = new ItemsData
        {
            value0 = splitLines[0],
            value1 = splitLines[1],
            value2 = splitLines[2],
            value3 = splitLines[3],
            value4 = splitLines[4],
        };
        items.Add(dataitem);
    }

    itemsControl.DataContext = items;
}