如何在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
答案 0 :(得分:4)
您在每次循环时都会替换您的项目。
首先,在循环之外创建您的集合:
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;
}