【问题标题】:ListBox/ListBoxItem for BoundData Style Template Clarification WPF XAMLBoundData 样式模板说明 WPF XAML 的 ListBox/ListBoxItem
【发布时间】:2012-11-30 12:54:44
【问题描述】:

如何让数据绑定的 ListBox 接受 ListBoxItem 的模板样式(从我的 ResourceDictionary 中与相应样式同名)?

我在 Blend 4 中看到,在 SimpleStyles ResourceDictionary 文件中,“SimpleListBoxItem”的属性设置为:

 d:IsControlPart="True"

但我只能在为 xaml 硬编码 ListBoxItem 显式使用 SimpleListBoxItem 样式时使用它?

对我来说有意义的是将样式应用于 ListBox 中的 ControlTemplate。我看到列表框中的控件模板如下所示:

ControlTemplate TargetType="{x:Type ListBox}">
                <Grid>
                    <Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" 
                            BorderThickness="{TemplateBinding BorderThickness}" 
                            Background="{TemplateBinding Background}"
                            />
                    <ScrollViewer Margin="1" Style="{DynamicResource SimpleScrollViewer}" Focusable="false" Background="{TemplateBinding Background}">

                        <!-- The StackPanel is used to display the children by setting IsItemsHost to be True -->
                        <StackPanel Margin="2" IsItemsHost="true"/>

                    </ScrollViewer>
                </Grid>

有没有办法在该堆栈面板中再放置一个嵌套的“ItemsHost”样式模板?也许是数据模板?

提前致谢,如果需要进一步说明,请告诉我!

【问题讨论】:

  • 我不清楚您要做什么...您只是想将模板应用于项目,如ItemTemplate?
  • @dbaseman:啊,也许就是这样。我只想从 ListBox 样式(和“控件”)模板中将模板应用于子 ListBoxItems
  • 所以我认为您正在使用 &lt;ListBox.Items&gt; 并列出 XAML 中的项目(而不是使用 ItemsSource)?
  • 我没有列出项目,我将 ItemsSource 属性绑定到我的数据上下文。谢谢你一直陪着我,我意识到那是多么的不清楚。
  • 哦,好吧...那么我认为ItemTemplate 绝对是要走的路。

标签: wpf listbox styles controltemplate listboxitem


【解决方案1】:

有两个选项可以将样式应用到 ListBox 样式中的项目,ItemContainerStyle 和 ItemTemplate。

1) ItemContainerStyle 适用于ListBoxItem 类型——设置列表中每个项目的容器样式:

<Style TargetType="ListBoxItem" x:Key="SimpleListBoxItem">
    <Setter Property="Background" Value="Green">
    <!-- etc -->
</Style>

<Style TargetType="ListBox" x:Key="ListBoxStyle">
    <Setter Property="ItemContainerStyle" Value="{StaticResource SimpleListBoxItem}">
</Style>

2) ItemTemplate 属性允许您完成重新定义每个项目如何显示的模板,例如:

<Style TargetType="ListBox" x:Key="ListBoxStyle">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="This is an item" />
                    <ContentControl Grid.Column="1" Text="{Binding}" />
                <Grid>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

【讨论】:

  • 太棒了。非常感谢。很好的解释。
  • @UB3571 我相信您仍然可以将#1 与#2 结合使用。无论您定义什么模板,它仍将被包装在ListBoxItem 容器中,这是您要设置边框的地方。使用 ItemContainerStyle 设置样式。
猜你喜欢
  • 1970-01-01
  • 2018-10-14
  • 1970-01-01
  • 2016-04-14
  • 2014-10-15
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多