我有一个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>
我还能在哪里听到这些焦点事件?
谢谢!
免责声明:我在微软工作
使用<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"));
}