我需要改变的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).
我点击的问题(只能通过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中属性。在code下面我创建2个数据模板:一个是未选中,另一个是选择的状态。然后,我创建了ItemContainerStyle,这是实际的ListBoxItem中包含该项目的模板。我设置默认的ContentTemplate到未选中状态,然后提供一个触发器,换出模板时的IsSelected属性为true。 (注:我设置了code中的的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}" />