我有一个程序,我正在读一个包含2列的.csv文件,我的模型有2个属性。 我读取该模型的实例,然后将它们添加到我的ObvervableCollection。
这是它的样子:
// My data field
private ObservableCollection<Model> _internalFile = new ObservableCollection<Model>();
// My data accessor/setter
public ObservableCollection<Model> InternalFile { get { return _internalFile; } set { _internalFile = value; } }
Model x = new Model();
while (fileReader.Peek() != -1)
{
// words = read the line, split the line, make a list of columns
var words = fileReader.ReadLine().Split(',').ToList();
if (words[0] != "Name")
{
x.asWord = words[0];
x.asNumber = int.Parse(words[1]);
InternalFile.Add(x);
// InternalFile is a collection of 'Model' objects.
// So created 'Model' placeholder , x, and pile each instance of x
// in the collection to be displayed.
}
}
我的XAML看起来像这样
<Window x:Class="WpfMVVP.WindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfMVVP"
Title="Window View" Height="350" Width="525" Background="White">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" AutoGenerateColumns="False" CanUserReorderColumns="False" ItemsSource="{Binding Path=InternalFile}">
<DataGrid.Columns>
<DataGridTextColumn Header="As Word" IsReadOnly="True" Width="Auto" Binding="{Binding asWord}" />
<DataGridTextColumn Header="As Number" IsReadOnly="True" Width="Auto" Binding="{Binding asNumber}" />
</DataGrid.Columns>
</DataGrid>
<Label Grid.Row="1" Content="{Binding Status}" />
</Grid>
在显示的窗口中,我看到列已填充,但所有行都是在文件结束前读取的最后一行。就好像ObservableCollection用新值覆盖它以前的元素一样。我不知道为什么会这样。
答案 0 :(得分:0)
您只需创建一次Model
,并在每次读取最后一次数据时覆盖它。您要做的是为每行读取创建一个新的Model
。您只需在while循环中移动Model
实例化即可。 (见下文)
// My data field
private ObservableCollection<Model> _internalFile = new ObservableCollection<Model>();
// My data accessor/setter
public ObservableCollection<Model> InternalFile { get { return _internalFile; } set { _internalFile = value; } }
while (fileReader.Peek() != -1)
{
Model x = new Model();
// words = read the line, split the line, make a list of columns
var words = fileReader.ReadLine().Split(',').ToList();
if ((words[0] != "Name") && (!String.IsNullOrEmpty(words[0]))
{
x.asWord = words[0];
x.asNumber = int.Parse(words[1]);
InternalFile.Add(x);
// InternalFile is a collection of 'Model' objects.
// So created 'Model' placeholder , x, and pile each instance of x
// in the collection to be displayed.
}
}