XAML 如何判断ListViewItem何时获得焦点?

z5btuh9x  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(129)

我有一个UWP XAML ListView,希望在使用箭头键在中的项目之间切换时处理焦点事件。但是,我不知道如何处理项目的焦点事件:

<ListView ItemsSource="{x:Bind Items}"
                  CanDragItems="True" CanReorderItems="True" AllowDrop="True"
                  SelectionMode="None" IsItemClickEnabled="True" ItemClick="ListView_ItemClick">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="x:String">
                    <!-- Never fires, even with Control.IsTemplateFocusTarget="True" : -->
                    <StackPanel GotFocus="StackPanel_GotFocus">
                        <!-- Never fires: -->
                        <TextBlock Text="{x:Bind}" GotFocus="TextBlock_GotFocus" />
                        <Button Content="Foo" IsTabStop="False" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="ListViewItem">
                                <!-- Never fires: -->
                                <ListViewItemPresenter [...]
                                                       GotFocus="Root_GotFocus" />
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListView.ItemContainerStyle>
        </ListView>

我还能在哪里听这些焦点事件?
谢谢你!
Disclaimer: I work for Microsoft.

rqqzpn5f

rqqzpn5f1#

当使用<ListView><ListBox>时,您不需要使用GotFocus事件,而是在主<listView>控件中使用SelectionChanged事件,并在代码中获取所选<ListViewItem>的索引。
每次用户在<ListView>中更改其选择时,都会触发SelectionChanged事件。
ListView.SelectedIndex返回所选<ListViewItem>的索引号第一项为0。
以下是一个示例:
XAML文件:

<Image x:Name="img"/>
<ListView x:Name="listView" SelectionChanged="ListView_SelectionChanged">  
<ListViewItem>Image 1</ListViewItem>
<ListViewItem>Image 2</ListViewItem> 
<ListViewItem>Image 3</ListViewItem>
</ListView>

C#:

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{                                                                                                                                                                                                                                                                           
    int num = listView.SelectedIndex + 1;                                                                         
    img.Source = new BitmapImage(new Uri($"ms-appx:///Assets/Pictures/image{num}.jpg"));
}

相关问题