【问题标题】:How to change WPF Listbox/ListBoxItem DataTemplate for selected item WITHOUT affecting style & theming?如何在不影响样式和主题的情况下更改所选项目的 WPF Listbox/ListBoxItem DataTemplate?
【发布时间】:2010-02-01 09:07:10
【问题描述】:

这个问题和Change WPF DataTemplate...非常相似,我已经阅读并实现了。起初它工作得很好,但我遇到了问题。

这个问题是,当在您的应用程序中使用主题时,例如 WPF Futures project(例如 Expression Dark)中的主题,ListBoxItems 都恢复为默认的 WPF 样式。这打破了这些元素的主题,例如,在黑色背景上生成黑色文本,否则文本将为白色。这也影响了我的 TreeView,并且可能会影响其他类似的控件。

我认为这是因为为 ListBox.ItemContainerStyle 设置了冲突的样式——一个来自主题,一个用于切换数据模板。

我四处寻找其他解决方案,但还没有找到任何东西。以下是我迄今为止的线索或想法:

  1. 子类化 DataTemplateSelector 并将其设置为 ListBox.ItemTemplateSelector。 (当前的最佳选择)。
  2. 不知何故,在某处使用了 Trigger、DataTrigger 或 EventTrigger。
  3. 放弃主题。
  4. 不知何故将我想要的功能加入到主题中。
  5. 不知何故,我的自定义 ItemContainerStyle 以某种方式从主题样式继承了它的颜色和眼睛糖果。 (我试了一下,还是不行。)

这是我的 ListBox 和相关部分:

<Window.Resources>

  <DataTemplate x:Key="NormalTemplate">
      ...
  </DataTemplate>

  <DataTemplate x:Key="SelectedTemplate">
      ...
  </DataTemplate>

</Window.Resources>

<ListBox x:Name="RegisterListBox" Grid.Row="0"
         HorizontalContentAlignment="Stretch"
         ItemsSource="{Binding Adjustments}">

    <!-- this is from the post referenced above -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="ContentTemplate" Value="{StaticResource NormalTemplate}"/>
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

在代码中设置 Listbox.DataContext 以启用 ItemsSource 绑定。

有什么想法可以实现上述功能,同时保持对主题的无缝支持?

【问题讨论】:

    标签: wpf templates xaml data-binding themes


    【解决方案1】:

    你试过做这样的事情吗?

    <ListBox.ItemContainerStyle>
        <Style 
            TargetType="{x:Type ListBoxItem}" 
            BasedOn="{StaticResource {x:Type ListBoxItem}}">    <=====
    ...
    

    这个想法是,框架将首先寻找一个 key 等于 typeof(ListBoxItem) 的样式,它会在主题中找到它,然后您的样式将使用您的具体细节扩展主题样式。

    【讨论】:

    • 成功了。我曾想过使用 BasedOn,但我认为我不能这样做,因为主题的样式没有键/名称。我从没想过将它指向类型。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多