Search code examples
c#xamluwpxbox-one

XAML detect if listview item is focused or not


I am trying to detect which item in a listview is focused, but I am not getting the events detected. I am developing for Xbox One UWP, so I cannot use mouse or keyboard events, only focus can be used.

<ListView.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Vertical" GotFocus="StackPanel_GotFocus" >
            <StackPanel Name="Imagestack" Orientation="Horizontal">
                <Image Source="{Binding Image}" Height="144" Width="256" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Title}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </StackPanel>
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>
private void StackPanel_GotFocus(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("Image focus");
    Image img = sender as Image;
    Bgimage.Source = img.Source;
}

Solution

  • You should register to the ListView.GotFocus event.

    The OriginalSource from the event parameter will be the ListViewItem which has received the focus. You can then retrieve the item content using ListViewItem.Content.

    XAML:

    <ListView x:Name="list" GotFocus="list_GotFocus">
         <ListView.ItemTemplate>...</ListView.ItemTemplate>
    </ListView>
    

    Code behind:

    private void list_GotFocus(object sender, RoutedEventArgs e)
    {
         var focusedItem = (e.OriginalSource as ListViewItem)?.Content; 
    }