我正在创建UWP项目。我正在使用listview来显示内容。将内容动态添加到listview并成功完成。当我在-1中选择内容 selectedIndex 值时,我遇到了一个问题。
<ListView Name="MyListView" IsItemClickEnabled="False" SelectionMode="Single" SelectionChanged="MyListView_SelectionChanged_1">
<ListView.ItemTemplate>
<DataTemplate>
<ListViewItem Height="80" Width="290" Tapped="ListViewItem_Tapped" Margin="-10,0,-10,0">
<StackPanel Orientation="Horizontal" Margin="-10,0,-24,0" HorizontalAlignment="Right" Width="288" >
<Border Background="#E94F08" Height="75" Margin="0,0,0,0" Width="288" CornerRadius="50" >
<StackPanel Orientation="Horizontal">
<Ellipse Height="68" Margin="5,0,0,0" Width="70" HorizontalAlignment="Left" >
<Ellipse.Fill>
<ImageBrush ImageSource="/Assets/4.jpg"/>
</Ellipse.Fill>
</Ellipse>
<TextBlock Margin="10,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{Binding Name }" Foreground="Black" FontSize="20">
</TextBlock>
</StackPanel>
</Border>
</StackPanel>
</ListViewItem>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
答案 0 :(得分:0)
你可以这样做,
<ListView x:Name="listViewName"
IsItemClickEnabled="True"
SelectionMode="Single"
SelectionChanged="listView_SelectionChanged">
</ListView>
private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int index = listViewName.SelectedIndex;
}
希望这会有所帮助:)
答案 1 :(得分:0)
您要做的第一件事就是从ListViewItem
中删除ItemTemplate
,因为您在该模板中放置的所有内容都已包含在ListViewItem
中。通过删除它,您还可以删除不正确的tapped事件处理程序。
下一步是设置IsItemClickEnabled="True"
而不是False
,告诉ListView
人们可以实际点击/点按您的商品。您无法处理SelectionChanged
事件或ItemClicked
事件,第二个事件的优点是同时注册了同一项目的多次点击(如果您需要)。
我将您的XAML更新为:
<ListView Name="MyListView" IsItemClickEnabled="True" SelectionMode="Single" SelectionChanged="MyListView_SelectionChanged_1">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="-10,0,-24,0" HorizontalAlignment="Right" Width="288" >
<Border Background="#E94F08" Height="75" Margin="0,0,0,0" Width="288" CornerRadius="50" >
<StackPanel Orientation="Horizontal">
<Ellipse Height="68" Margin="5,0,0,0" Width="70" HorizontalAlignment="Left" >
<Ellipse.Fill>
<ImageBrush ImageSource="/Assets/4.jpg"/>
</Ellipse.Fill>
</Ellipse>
<TextBlock Margin="10,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{Binding Name }" Foreground="Black" FontSize="20">
</TextBlock>
</StackPanel>
</Border>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
如果您需要SelectedItem而不是索引,那么绑定SelectedItem属性可能更容易。别忘了在绑定上使用Mode = TwoWay。