WPF使用MVVM模式创建动态行

时间:2009-07-23 05:22:49

标签: wpf mvvm datatemplate

我想用动态行加载我的WPF UserControl。我的方案如下。

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 个答案:

答案 0 :(得分:1)

将您拥有的MVVM对象设置为UserControl的dataContext,我希望该对象中包含Collection属性。然后创建一个更像下面的ItemsControl 从您的描述中不清楚标签和项目究竟来自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>