如果选中,请更改 ListBox 项目的 WPF DataTemplate [英] Change WPF DataTemplate for ListBox item if selected

查看:36
本文介绍了如果选中,请更改 ListBox 项目的 WPF DataTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据项目是否被选中(选择时显示不同/更多信息)来更改 ListBox 中项目的 DataTemplate.

I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected).

当我点击有问题的 ListBox 项目(仅通过 Tab 键)时,我没有在 DataTemplate(一个 StackPanel)的最顶层元素上收到 GotFocus/LostFocus 事件,而且我没有想法.

I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas.

推荐答案

最简单的方法是为ItemContainerStyle"而不是ItemTemplate"属性提供模板.在下面的代码中,我创建了 2 个数据模板:一个用于未选中"状态,一个用于选中"状态.然后我为ItemContainerStyle"创建一个模板,它是包含该项目的实际ListBoxItem".我将默认的ContentTemplate"设置为Unselected"状态,然后提供一个触发器,当IsSelected"属性为真时交换模板.(注意:为简单起见,我将后面代码中的ItemsSource"属性设置为字符串列表)

The easiest way to do this is to supply a template for the "ItemContainerStyle" and NOT the "ItemTemplate" property. In the code below I create 2 data templates: one for the "unselected" and one for the "selected" states. I then create a template for the "ItemContainerStyle" which is the actual "ListBoxItem" that contains the item. I set the default "ContentTemplate" to the "Unselected" state, and then supply a trigger that swaps out the template when the "IsSelected" property is true. (Note: I am setting the "ItemsSource" property in the code behind to a list of strings for simplicity)

<Window.Resources>

<DataTemplate x:Key="ItemTemplate">
    <TextBlock Text="{Binding}" Foreground="Red" />
</DataTemplate>

<DataTemplate x:Key="SelectedTemplate">
    <TextBlock Text="{Binding}" Foreground="White" />
</DataTemplate>

<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
    <Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
        </Trigger>
    </Style.Triggers>
</Style>

</Window.Resources>
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource ContainerStyle}" />

这篇关于如果选中,请更改 ListBox 项目的 WPF DataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆