我是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。我不必使用堆栈面板,但只是认为我会用这个样本。
谢谢!这是一个非常干净的解决方案,我也喜欢你如何在ListBox.ItemTemplate属性中嵌入数据模板。我没有想过这样做。 – 2010-04-27 13:28:35
很乐意帮忙。当然,你没有**必须把它放在项目模板中 - 你也可以为你的类型定义一个DataTemplate。 – 2010-04-27 13:48:04