views:

460

answers:

1

Hi,

I want to load my WPF UserControl with dynamic rows. My scenario is as follows.

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

Column 1 is a Label Control and Column 2 will be a TextBlock control

   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.

Note: I'm using the MVVM toolkit from CodePlex.

Thanks, Jithu

A: 

Set the MVVM object you have as the dataContext of your UserControl, I hope the object has a Collection property in it. Then create an ItemsControl more like below It is not clear from your description that where is really the Label and Item comes from your ViewModel. The below code will create Rows dynamically as many as your 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>
Jobi Joy