How to highlight selected item in ItemsControl?

a 夏天 提交于 2019-11-28 11:07:16
Rachel

An ItemsControl does not track the SelectedItem

If you want that behavior, I would suggest overwriting the styles and templates for a ListBox

<ListBox Name="itemsCtrl" HorizontalContentAlignment="Center" ItemsSource="{Binding Path=MovieCollection, Mode=TwoWay}">

    <ListBox.Resources>
        <!-- Set SelectedItem Background here -->
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow"/>
    </ListBox.Resources>

    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="5" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemTemplate>
        <DataTemplate>
                <StackPanel Orientation="Vertical" HorizontalAlignment="Center">
                    <Image Style="{StaticResource ImageHover}" Margin="0,5,0,0" RenderOptions.BitmapScalingMode="HighQuality" SnapsToDevicePixels="True" HorizontalAlignment="Center" Source="{Binding Path=Poster}" Height="150" />
                    <TextBlock Name="txtTitle" FontSize="10" HorizontalAlignment="Center" TextAlignment="Justify" Text="{Binding Title}" TextWrapping="Wrap" MaxWidth="110" />
                </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

you can also do this through the expression blend interactivity. Use the event name MouseLeftDown or Tapped Event (in Windows 8.1) in the ItemsTemplate in the top container (StackPanel or the grid).

xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseLeftDown">
        <Core:ChangePropertyAction PropertyName="Background" Value="Green"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

This should do the trick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!