listview中的第二项不能正确呈现第一次

时间:2016-04-02 16:34:24

标签: c# wpf listview

所以我有这个问题,我有一个listview,当我添加它渲染的第一个项目,但第二个不渲染,但listview所在的面板增长,就像它一样。然后,如果第三个项目同时添加第二个和第三个渲染。之后,添加的每个新项目立即呈现。此问题仅适用于第二项。

XAML:

<ListView Name="DownloadList" Background="WhiteSmoke" PreviewMouseLeftButtonUp="DownloadList_PreviewMouseLeftButtonUp" Width="649" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.View>                  
        <GridView>
            <GridViewColumn Width="140" Header="Name" DisplayMemberBinding="{Binding Name}"/>
            <GridViewColumn Width="80" Header="Status" DisplayMemberBinding="{Binding Status}"/>
            <GridViewColumn Width="60" Header="Size" DisplayMemberBinding="{Binding FormattedSize}"/>
            <GridViewColumn Width="70" Header="Speed" DisplayMemberBinding="{Binding FormattedSpeed}"/>
            <GridViewColumn Width="170" Header="Progress">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                            <Grid>
                                <ProgressBar Name ="dlPrgrs" Height ="20" Width="150" Maximum="100" Value="{Binding FormattedProgress}" Foreground="{Binding ForColor}"/>
                                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding ElementName=dlPrgrs, Path=Value, StringFormat={}{0:0}%}"/>
                            </Grid>
                        </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Width="65" Header="Time Left" DisplayMemberBinding="{Binding FormattedTime}"/>
            <GridViewColumn Width="60" Header="Peers" DisplayMemberBinding="{Binding Peers}"/>
         </GridView>
     </ListView.View>
</ListView>   
代码背后的

列表创建和绑定:

List<FileDownload> wpfDownloads = new List<FileDownload>();
DownloadList.ItemsSource = wpfDownloads;

添加新项目:

wpfDownloads.Add(download);

感谢

1 个答案:

答案 0 :(得分:1)

只需使用ObservableCollection<FileDownload>代替List<FileDownload>。 导致ObservableCollection<T>已实施INotifyCollectionChanged接口。

As MSDN says:

  

INotifyCollectionChanged通知听众动态变化等   当添加和删除项目或清除整个列表时。

有关您的用户界面的简单建议:

我建议你创建可调整大小的XAML,而不是静态的。我的意思是它很糟糕:

<Grid>        
   <ListView HorizontalAlignment="Left" Margin="10">
       ...The code omitted for the brevity...
   </ListView>
   <Button Margin="50" Name="btn_add" Click="btn_add_Click" Content="Add new item"/>
</Grid>

但是,它更好,并且此UI(XAML)可以调整大小:

<Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="5*">
      </RowDefinition>
    </Grid.RowDefinitions>  
    <ListView HorizontalAlignment="Left">
       ...The code omitted for the brevity...
    </ListView>
    <Button Grid.Row="1" Name="btn_add" Click="btn_add_Click" Content="Add new item"/>
</Grid>