【问题标题】:Why are ListBoxItems added in XAML not styled?为什么 XAML 中添加的 ListBoxItems 没有设置样式?
【发布时间】:2013-08-10 15:22:37
【问题描述】:

为什么在 XAML 中声明的 ListBoxItems 不受 DataTemplate 的影响?当我绑定源时,模板很好,这就是我最终要做的,但只是想知道为什么声明的项目没有样式。

<ListBox>
     <ListBox.ItemTemplate>
         <DataTemplate>
             <Grid>
                 <TextBlock Text="{Binding}" Foreground="Red"/>
             </Grid> 
         </DataTemplate>                   
     </ListBox.ItemTemplate>
     <ListBoxItem>LBI 1</ListBoxItem>
     <ListBoxItem>LBI 2</ListBoxItem>
</ListBox>

这里的 LBI 1 和 LBI 2 不是红色的,但如果我使用 ListBox.ItemSource 并绑定一个列表,项目是红色的。

【问题讨论】:

    标签: c# silverlight xaml listbox datatemplate


    【解决方案1】:

    "在ItemsControl上设置ItemTemplate时,生成的UI如下(以ListBox为例):

    1. 在内容生成期间,ItemsPanel 向 ItemContainerGenerator 发起请求,以便为每个数据项创建一个容器。对于 ListBox,容器是 ListBoxItem。生成器回调 ItemsControl 以准备容器。

    2. 部分准备工作包括将 ListBox 的 ItemTemplate 复制为 ListBoxItem 的 ContentTemplate。

    3. 与所有 ContentControl 类型类似,ListBoxItem 的 ControlTemplate 包含一个 ContentPresenter。应用模板时,它会创建一个 ContentPresenter,其 ContentTemplate 绑定到 ListBoxItem 的 ContentTemplate。

    4. 最后,ContentPresenter 将 ContentTemplate 应用到自身,然后创建 UI。”

    如您所见above,数据模板仅用于新生成的项目。此外,数据模板通常用于描述/呈现"the visual structure" 的数据 - 您的 ListBoxItems 已经被描述为 ListBoxItems,因此他们使用该模板......希望这是有道理的......

    【讨论】:

      【解决方案2】:

      您需要申请StyleDataTemplate 用于将模板应用于绑定到 listBox 的Data。因此不适用于在 XAML 中直接作为子项添加的项目。

          <ListBox>
              <ListBox.Resources>
                  <Style TargetType="ListBoxItem">
                      <Setter Property="Foreground" Value="Red"/>
                  </Style>
              </ListBox.Resources>
              <ListBoxItem>LBI 1</ListBoxItem>
              <ListBoxItem>LBI 2</ListBoxItem>
          </ListBox>
      

      【讨论】:

      • 谢谢,这就是我想要的。我猜数据方面是在名称中! :)(时间到了我会接受)
      【解决方案3】:

      因为示例中的 LB1 和 LB2 不是数据模板的一部分。当你将一些数据绑定到你的 ListBox 的 ItemsSource 时,这些项目将根据数据模板显示。

      【讨论】:

        猜你喜欢
        • 2020-07-02
        • 2018-09-23
        • 2021-07-13
        • 2012-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多