先上个示例
<ItemsControl Margin="10" ItemsSource="{Binding}" Name="itemsControl">
<ItemsControl.Template><ControlTemplate TargetType="{x:Type ItemsControl}"><Border CornerRadius="5"><ScrollViewer VerticalScrollBarVisibility="Auto" ><ItemsPresenter /></ScrollViewer></Border></ControlTemplate></ItemsControl.Template><ItemsControl.ItemsPanel><ItemsPanelTemplate><WrapPanel Name="wp" /></ItemsPanelTemplate></ItemsControl.ItemsPanel><ItemsControl.ItemTemplate><DataTemplate><Image Source="{Binding XPath=@}" /></DataTemplate></ItemsControl.ItemTemplate></ItemsControl>
ItemsControl 是一种数据展示控件,大致分为三个部分组成:Template, ItemTemplate, ItemsPanel.
- 先说 Template ,Template 是整个控件的架构设计,最外面放什么的东东,里面放什么东东,都在这里控制,负责宏观的结构,下面这个例子:最外面是一个border,然后要放一个ScrollViewer用来滚动展示,滚动的内容,就由ItemsPresenter 来决定。对应blend菜单:右键—>Edit Template
<ItemsControl.Template>
<ControlTemplate TargetType="{x:Type ItemsControl}">
<Border CornerRadius="5">
<ScrollViewer VerticalScrollBarVisibility="Auto" >
<ItemsPresenter />
</ScrollViewer>
</Border>
</ControlTemplate>
</ItemsControl.Template>
2. 再说ItemsPanel,作为数据展示,总要有个容器吧,这个panel就是为了设置容器用的,设置为StackPanel,WrapPanel都可以,足够灵活,对应上一条中的ItemsPresenter,
对应blend菜单 :右键--àEdit Additional TemplatesàEdit Layout Items(ItemsPanel)
例如:
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Name="wp" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
3. 最后是ItemTemplate , 每一个数据条目应该是个什么样子,负责具体呈现的,例如数据项是一个图片,那就用图片来显示,
对应blend菜单 :右键--à Edit Additional TemplatesàEdit Generated Items(ItemsTemplate)
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding XPath=@}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
4. 附带一个,ItemContainerStyle ,也就是控制每个数据条目的显示样式,例如,想要在上例中的Image外面加一个边框,
对应blend菜单 :右键--à Edit Additional TemplatesàEdit Generated Item Container (ItemContainerStyle)
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border BorderBrush="Black" BorderThickness=".5" Height="100">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemContainerStyle>
搞了很久才明白这么多东东,感觉微软把这事搞复杂了,要是像asp.net 里面repeater或者datalist那种弄法,会简单很多哦。