您可能需要一个ItemsControl。它允许您使用指定的DataTemplate呈现一系列项目。您可以在ItemsControl中内联执行此操作:
<ItemsControl ItemsSource="">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked=""/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
或者直接从资源中显式地引用数据模板......更像是这样:
<!-- In some parent resource section -->
<DataTemplate x:Key="MyDataTemplateName">
<CheckBox IsChecked="{Binding NameOfTheCheckedPropertyOnEachItem}"/>
</DataTemplate>
<!-- ... -->
<ItemsControl ItemsSource="{Binding MyCollectionOfItems}" ItemTemplate="{StaticResource MyDataTemplateName}">
</ItemsControl>
或者您可以定义一个 DataTemplate 来定义绑定类的外观和感觉。(请注意,如果您的 Linq-to-SQL 投影到匿名类型中,这不是一个选项) 示例:
<!-- In some parent resource section -->
<DataTemplate DataType="">
<CheckBox IsChecked=""/>
</DataTemplate>
<!-- ... -->
<ItemsControl ItemsSource="">
</ItemsControl>
WPF将会寻找与集合中每个项目的DataType匹配的DataTemplate。请注意,这对于需要不同呈现方式的异构集合的绑定非常有用。
你可以绑定Stackpanel的DataContext,但是它没有关于为数据的每个元素重复使用模板的内在逻辑。它只是为子控件和包含的{Binding ...}语句提供上下文。所有处理重复数据的控件都是从ItemsControl派生的,并通过ItemsSource属性接收它们的数据。