0

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

应用程序窗口

4

1 回答 1

0

您只创建Model一次,并在每次读取最后一次数据时覆盖它。您要做的是Model为读取的每一行创建一个新的。您可以简单地将您的Model实例化移动到您的 while 循环中。(见下文)

// 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. 
      }
  }
于 2013-04-22T16:58:17.963 回答