【问题标题】:What's the difference between ItemTemplate and ItemContainerStyle in a WPF ListBox?WPF ListBox 中的 ItemTemplate 和 ItemContainerStyle 有什么区别?
【发布时间】:2016-02-10 23:50:39
【问题描述】:

在 WPF Listbox 中,我对以下两个概念感到困惑: ItemTemplateItemContainerStyle 谁能给我解释一下?

【问题讨论】:

标签: wpf listbox itemtemplate itemcontainerstyle


【解决方案1】:

ItemTemplate 用于设置数据项内容的显示方式。您可以使用它来绑定数据字段、格式化显示字符串等等。它决定了数据的呈现方式。

ItemContainerStyle 用于设置数据项容器的样式。在列表框中,这将是一个 ListBoxItem。此处的样式会影响选择行为或背景颜色等内容。它决定了显示器的风格和用户体验。

上面链接的 ItemContainerStyle 的 MSDN 页面有一个很好的示例,显示了一些差异:

 <!--Use the ItemTemplate to set a DataTemplate to define
      the visualization of the data objects. This DataTemplate
      specifies that each data object appears with the Proriity
      and TaskName on top of a silver ellipse.-->
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <DataTemplate.Resources>
        <Style TargetType="TextBlock">
          <Setter Property="FontSize" Value="18"/>
          <Setter Property="HorizontalAlignment" Value="Center"/>
        </Style>
      </DataTemplate.Resources>
      <Grid>
        <Ellipse Fill="Silver"/>
        <StackPanel>
          <TextBlock Margin="3,3,3,0"
                     Text="{Binding Path=Priority}"/>
          <TextBlock Margin="3,0,3,7"
                     Text="{Binding Path=TaskName}"/>
        </StackPanel>
      </Grid>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
  <!--Use the ItemContainerStyle property to specify the appearance
      of the element that contains the data. This ItemContainerStyle
      gives each item container a margin and a width. There is also
      a trigger that sets a tooltip that shows the description of
      the data object when the mouse hovers over the item container.-->
  <ItemsControl.ItemContainerStyle>
    <Style>
      <Setter Property="Control.Width" Value="100"/>
      <Setter Property="Control.Margin" Value="5"/>
      <Style.Triggers>
        <Trigger Property="Control.IsMouseOver" Value="True">
          <Setter Property="Control.ToolTip"
                  Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                          Path=Content.Description}"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </ItemsControl.ItemContainerStyle>

【讨论】:

    【解决方案2】:

    ItemContainerStyle 只是 DataTemplate 的包装器,因此可以将通用项样式应用于不同的数据布局。

    另外,来自this answer to "DataTemplate vs ItemContainerStyle"

    您可以在 ItemTemplate 中进行所有样式设置,但 ItemContentStyle 具有 VisualStates,可控制鼠标悬停/禁用/选择等时的不透明度。

    如果您想更改这些不透明度状态更改,或者如果您想要矩形以外的任何容器形状,例如三角形,那么您必须覆盖默认的 ItemContainerStyle。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-09
      • 2014-08-16
      • 2013-02-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 2011-01-25
      相关资源
      最近更新 更多