我需要根据是否选择项目来更改列表框中项目的数据模板(选择时显示不同/更多信息)。
当单击相关的 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/