我有一个程序,我正在读取一个包含 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 正在用新值覆盖其先前的元素。我不知道它为什么会这样。