【问题标题】:How do I apply a Style Setter for ListBoxItems of a certain DataType?如何为特定数据类型的列表框项应用样式设置器?
【发布时间】:2011-11-24 10:08:37
【问题描述】:

我的 WPF ListBox 包含两种类型的对象:产品和品牌。

我希望我的产品可供选择。我想要我的品牌不可选。

这两种类型中的每一种都有自己的 DataTemplate。

默认情况下,可以选择任何东西:

<ListBox ... >
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type local:Product}">
            ...
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:Brand}">
            ...
        </DataTemplate>
    </ListBox.Resources>
</ListBox>

我可以使用 Setter 设置 Focusable,但是可能会选择 nothing:

<ListBox ... >
    <ListBox.Resources>
        ...
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Focusable" Value="False" />
        </Style>
    </ListBox.Resources>
</ListBox>

我无法将 Setter 放在 DataTemplate 中。

我无法将 DataType 放到 Style 上。

如何仅设置 Brand 类型的 ListBoxItems 的样式?

【问题讨论】:

    标签: wpf xaml styles datatemplate listboxitem


    【解决方案1】:

    感谢 StyleSelector 类,您可以根据 ItemContainerStyle 的数据类型附加样式。这里有一个很好的例子:http://www.telerik.com/help/wpf/common-data-binding-style-selectors.html

    【讨论】:

      【解决方案2】:

      您可以在 ListBoxItem 样式上使用数据触发器吗?如果是这样,请绑定到 DataContext(您的类)并使用值转换器来测试类型。如果它是您感兴趣的,请设置 ListBoxItem 的样式,使其无法显示为选中状态。

      我认为您不能在没有代码隐藏或自定义行为的情况下禁止选择 Selector(ListBox 的父级)中的项目。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 2012-08-10
        • 2022-11-28
        • 2020-02-14
        • 2018-03-15
        • 2022-08-11
        • 2014-12-06
        相关资源
        最近更新 更多