我有一個程序,我正在讀取一個帶有2列的.csv文件,而我的模型有2個屬性。 我讀取這個模型的實例,然後將它們添加到我的ObvervableCollection中。在數據網格列中顯示ObservableCollection的元素
這裏是什麼樣子:
// 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正在用新值覆蓋以前的元素。我不知道爲什麼它會這樣。
'File.ReadAllLines(文件名)。選擇(X => x.Split( ''))。選擇(X =>新型號的{Name = X [0],AsNumber = int.Parse(x [1]))' – Will 2013-04-22 20:22:00