2010-04-26 53 views
2

我是Silverlight的新手,所以我没有掌握所有可用的控件。我想要做的是使用数据绑定和视图模型来维护项目的集合。这里是想我做一些模拟代码:Silverlight数据绑定在堆栈面板中收集

型号

public class MyItem 
    { 
     public string DisplayText { get; set; } 
     public bool Enabled { get; set; } 
    } 

视图模型

public class MyViewModel : INotifyPropertyChanged 
{ 
     private ObservableCollection<MyItem> _myItems = new ObservableCollection<MyItem>(); 
     public ObservableCollection<MyItem> MyItems 
     { 
      get { return _myItems; } 
      set 
      { 
       _myItems = value 
       NotifyPropertyChanged(this, "MyItems"); 
      } 
     } 
} 

查看

<Grid x:Name="LayoutRoot" Background="White"> 
     <StackPanel ItemsSource="{Binding MyItems}">    
      <StackPanel Orientation="Horizontal"> 
       <CheckBox "{Binding Enabled, Mode=TwoWay}"></CheckBox> 
       <TextBlock Text="{Binding DisplayText, Mode=TwoWay}" /> 
      </StackPanel>     
     </StackPanel>   
    </Grid> 

所以我的最终目标是每次向MyItems集合添加另一个MyItem时,它都会创建一个带有复选框和文本块的新StackPanel。我不必使用堆栈面板,但只是认为我会用这个样本。

回答

5

看起来像你想<ListBox>,然后设置<ListBox.ItemTemplate><StackPanel>这样的事情.....

<ListBox ItemsSource=”{Binding Classes, Source={StaticResource model}}”>   
    <ListBox.ItemTemplate>    
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <CheckBox "{Binding Enabled, Mode=TwoWay}"/> 
       <TextBlock Text="{Binding DisplayText, Mode=TwoWay}" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

here is a great example(这是WPF,但只应为Silverlight微小的变化)

+0

谢谢!这是一个非常干净的解决方案,我也喜欢你如何在ListBox.ItemTemplate属性中嵌入数据模板。我没有想过这样做。 – 2010-04-27 13:28:35

+0

很乐意帮忙。当然,你没有**必须把它放在项目模板中 - 你也可以为你的类型定义一个DataTemplate。 – 2010-04-27 13:48:04

1

是的,看起来像你想有一个<ListBox>

<UserControl 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
x:Class="SilverlightApplication4.MainPage" 
Width="640" Height="480"> 
<UserControl.Resources> 
    <DataTemplate x:Key="ItemTemplate"> 
     <StackPanel Orientation="Horizontal"> 
      <CheckBox IsChecked="{Binding Enabled, Mode=TwoWay}"/> 
      <TextBlock Text="{Binding DisplayText}"/> 
     </StackPanel> 
    </DataTemplate> 
</UserControl.Resources> 
<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource SampleDataSource}}"> 
    <ListBox Margin="0,0,8,0" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Collection}"/> 
</Grid> 

此代码将为您提供一个ListBox,并将所有数据绑定到复选框和TextBlock,首先使用复选框,然后使用TextBox旁边的TextBox。