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 に答える