WPF ListBox中ItemTemplate和ItemContainerStyle有什么区别?

RHa*_*uda 42 wpf listbox itemtemplate itemcontainerstyle

在WPF中Listbox,我很困惑与这些概念2: ItemTemplateItemContainerStyle 一个人能更给我解释一下?

Eso*_*ame 44

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>
Run Code Online (Sandbox Code Playgroud)


小智 10

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

另外,从这个回答"DataTemplate vs ItemContainerStyle":

你可以做你的造型在ItemTemplate但ItemContentStyle具有过压/禁用/选择等控制鼠标的透明度VisualStates

如果要更改这些不透明度状态更改,或者如果您想要除矩形之外的任何容器形状(例如三角形),则必须覆盖默认的ItemContainerStyle.

  • 我*强烈*建议你更明显地说文本`你可以在ItemTemplate中做你所有的样式,但ItemContentStyle有VisualStates控制鼠标悬停/禁用/选择的不透明度`和`如果你想改变那些不透明状态更改,或者如果您想要除矩形之外的任何容器形状(例如三角形),那么您必须覆盖默认的ItemContainerStyle.已从提供的链接中复制; 他们最近一直在打击抄袭,这可以被视为. (2认同)