ItemsControl, ItemsPanel and ItemsPresenter (Silverlight, XAML)

随声附和 提交于 2019-12-03 11:06:47

问题


I'm utterly confused by these 3 terms, when to use which? What's the relationship and they are children of which controls?

Is it correct to say this is the tree:

ItemsControl > ItemsPresenter > ItemsPanel


回答1:


ItemsControl is conceptually a control that houses items. Try to simply think of this control as a holder for zero or more objects.

ItemsPresenter is a bit tougher to explain, but this is part of the ItemsControl template that will define where the items are placed within it. Your ItemsControl's template can be anything you like, say a Grid with some pretty pictures around it, inside this template, you would place the ItemsPresenter where ever you want your items to be, say right in the middle of your grid. (this example is taken from msdn and simplified for ease of reading)

<Style TargetType="HeaderedItemsControl">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type HeaderedItemsControl}">
          <Grid>
            <Rectangle Stroke="Black" Fill="Red"/>
            <ItemsPresenter Margin="2,0,0,0"/>
          </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

The ItemsPanel is the panel (or container) that controls the layout of the items in your ItemsControl. So if you want your items that you have added to your ItemsControl to display in a horizotal way, then yor items panel could simply be a StackPanel with its Orientation property set to Horizontal.

This all make sense?




回答2:


I think that this pretty much explains how the things are done by Silverlight: ItemsPanelTemplate Class: Specifies the panel that the ItemsPresenter creates for the layout of the items of an ItemsControl. ItemsPanelTemplate Class

 <Style TargetType="local:myItemsControl">
     <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical"/>
            </ItemsPanelTemplate>
        </Setter.Value>
     </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:myItemsControl">
              ....
               <ItemsPresenter />
              ....

Basically, the ItemPresenter (specified in the Template) will be replaced with whatever is specified in the ItemsPanelTemplate.

So, the Template can be extended to include a header and all child will be placed under this header:

<Grid> <TextBlock Text="Header"/>   <ItemsPresenter /> </Grid>


来源:https://stackoverflow.com/questions/3723893/itemscontrol-itemspanel-and-itemspresenter-silverlight-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!