2

为什么在 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 并绑定一个列表,则项目是红色的。

4

3 回答 3

3

“在 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。”

正如您在上面看到的,数据模板仅用于新生成的项目。此外,数据模板通常用于描述/呈现数据的“视觉结构” - 您的 ListBoxItems 已经被描述为 ListBoxItems,因此他们使用该模板......希望这是有道理的......

于 2013-08-10T15:56:27.930 回答
2

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

于 2013-08-10T15:26:29.873 回答
2

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

    <ListBox>
        <ListBox.Resources>
            <Style TargetType="ListBoxItem">
                <Setter Property="Foreground" Value="Red"/>
            </Style>
        </ListBox.Resources>
        <ListBoxItem>LBI 1</ListBoxItem>
        <ListBoxItem>LBI 2</ListBoxItem>
    </ListBox>
于 2013-08-10T15:28:23.580 回答