2009-07-23 85 views
0

我想用動態行加載我的WPF UserControl。我的情況如下。WPF使用MVVM模式創建動態行

1. When the UserControl gets loaded, I will populate my List<string> object with some values which I will get from a database. 
2. I need to create equal number of rows in my UserControl which matches the number of items in the List<string> object. The display will look something like below 

色譜柱1是一個標籤控制和第2列將是一個TextBlock控制

Label 1: Item 1 (This is the value from the List<string> object) 
    Label 2: Item 2 
    Label 3: Item 3 

I know how to create rows dynamically but my problem is how do I do this when I'm using the MVVM pattern. 

注:我使用從CodePlex上MVVM工具包。

感謝, Jithu

回答

1

設置你作爲你的用戶控件的的DataContext MVVM對象,希望對象中有一個集合屬性。然後創建一個ItemsControl,如下所示 從您的描述中不清楚Label和Item來自哪裏ViewModel。下面的代碼將動態創建與您的Collection.Count一樣多的行。

<ItemsControl ItemsSource="{Binding YourStringCollection}" HorizontalAlignment="Left" > 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
        <StackPanel Orientation="Vertical"/>    
      </ItemsPanelTemplate>        
     </ItemsControl.ItemsPanel> 
     <ItemsControl.ItemsTemplate> 
      <DataTemplate> 
        <TextBlock Text="{Binding}">    
      </DataTemplate >        
     </ItemsControl. ItemsTemplate > 
    </ItemsControl>