.net - 更改列表框项目的 WPF 数据模板(如果选择)

标签 .net wpf

我需要根据是否选择项目来更改列表框中项目的数据模板(选择时显示不同/更多信息)。

当单击相关的 ListBox 项(仅通过 Tab 键切换)时,我没有在 DataTemplate(StackPanel)的最顶层元素上收到 GotFocus/LostFocus 事件,而且我没有主意。

最佳答案

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

<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}" />

关于.net - 更改列表框项目的 WPF 数据模板(如果选择),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/146269/

相关文章:

c# - 从 json 字符串中提取信息并将其添加到 C# 中的列表

.net - 用于返回计算机上 .NET Framework 版本的 PowerShell 脚本?

c# - WPF:设置属性不会在文本框值更改时触发

.net - 可以将 ASP.NET 编译为机器代码吗?

c# - 根据配置部署不同的 WCF .svc 文件

c# - ASP.NET MVC 模型混淆

wpf - 如何在 WPF TreeView 中突出显示整行

c# - WPF 绑定(bind)到数组/集合

c# - 在DataGrid wpf中更改组合框的选定值

c# - 图像未显示在设计器、Silverlight 应用程序中