2015-05-31 60 views
2

我有我的目標,我想添加到我的ListViewWPF:添加多個對象到我的ListView - 只有第一個加入

Public class MyData 
{ 
    string name {get; set;} 
} 

這是我嘗試添加代碼隱藏我的對象:

ObservableCollection<MyData> collection = new ObservableCollection<MyData>(); 
      MyData data1 = new MyData("c:\file.doc"); 
      collection.Add(data1); 
      myListView.Items.Add(collection); 

這工作正常,但如果我想補充另一個問題:

ObservableCollection<MyData> collection = new ObservableCollection<MyData>(); 
      MyData data1 = new MyData("c:\file.doc"); 
      collection.Add(data1); 

      MyData data2 = new MyData("c:\blabla.doc"); 
      collection.Add(data2); 

      myListView.Items.Add(collection); 

,我只能看到第一個對象。

ListView XAML:

<ListView Name="myListView" Margin="16,453,263,40" Background="Transparent" BorderThickness="0" > 
     <ListView.ItemContainerStyle> 
      <Style TargetType="{x:Type ListViewItem}"> 
       <Setter Property="Foreground" Value="White"/> 
      </Style> 
     </ListView.ItemContainerStyle> 
     <ListView.Resources> 
      <DataTemplate x:Key="MyDataTemplate"> 
       <Grid Margin="-6"> 
        <ProgressBar Maximum="100" Value="{Binding Progress}" 
           Width="{Binding Path=Width, ElementName=ProgressCell}" Height="16" Margin="0" 
           Foreground="#FF5591E8" /> 
        <Label Content="{Binding Progress, StringFormat={}{0}%}" FontSize="12" 
          VerticalAlignment="Center" HorizontalAlignment="Center" /> 
       </Grid> 
      </DataTemplate> 
      <ControlTemplate x:Key="ProgressBarTemplate"> 
       <Label HorizontalAlignment="Center" VerticalAlignment="Center" /> 
      </ControlTemplate> 
     </ListView.Resources> 
     <ListView.View> 
      <GridView ColumnHeaderContainerStyle="{StaticResource ListViewHeaderStyle}"> 
       <GridViewColumn Width="425" Header="File name" DisplayMemberBinding="{Binding FileName}" /> 
       <GridViewColumn x:Name="ProgressCell" Width="50" Header="Progress" 
           CellTemplate="{StaticResource MyDataTemplate}" /> 
      </GridView> 
     </ListView.View> 
    </ListView> 
+0

您可以發佈您的XAML。 – Contango

+0

我會建議使用綁定來做到這一點。我強烈建議學習MVVM模式,它爲我創建可用的,可維護的技術債務免費應用程序提供了很好的幫助。 – Contango

+1

查看我的更新請 –

回答

3

定義集合,如下所示:

public ObservableCollection<Data> dataList { get; set; } 

初始化它在你的構造函數,並根據你的需要添加的元素。 設置你的窗口的數據上下文:

this.DataContext = this; 

然後數據將其綁定在XAML:

<ListView Name="myListView"     
      ItemsSource="{Binding dataList}"/> 

它應該工作,你應該看到添加的兩個元素。

對於您的具體情況,請勿將集合添加到Items中,而是設置ListView的ItemsSource。

myListView.ItemsSource = collection; 
+0

Items.Add ..和ItemSource有什麼區別?如果我會選擇添加多個項目會發生什麼?我會看到正在添加的項目或僅在最後我會突然看到所有文件? –

+0

Items.Add一次添加一個項目。因此,如果您想使用它,請嘗試使用foreach迭代您的集合,並在每個項目上使用myListView.Items.Add()。 –

相關問題