如果选择了更改ListBox项目的WPF DataTemplate

时间:2020-03-06 14:50:53  来源:igfitidea点击:

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

单击有问题的ListBox项(仅通过制表键)时,在DataTemplate(堆栈面板)的最顶层元素上没有出现GotFocus / LostFocus事件,并且我没有主意。

解决方案

最简单的方法是为" ItemContainerStyle"而不是" ItemTemplate"属性提供模板。在下面的代码中,我创建2个数据模板:一个用于"未选中"状态,一个用于"选中"状态。然后,我为" ItemContainerStyle"创建一个模板,该模板是包含该项目的实际" ListBoxItem"。我将默认的" ContentTemplate"设置为" Unselected"状态,然后提供一个触发器,当" 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}" />

还应该注意的是,堆栈面板不可操纵,因此它永远不会获得焦点(如果我们/ really /希望将其聚焦,则将其设置为Focusable = True)。但是,在这种情况下要记住的关键是Stackpanel是TreeViewItem的子级,在这种情况下,它是ItemContainer。正如Micah所建议的那样,调整itemcontainerstyle是一个好方法。

我们可能可以使用DataTemplates进行操作,诸如datatriggers之类的事情将使用RelativeSouce标记扩展来查找listviewitem