因此我无法在点击事件中找回正确的SelectedIndex。无论我选择什么项目,我都会回来-1
这是我的活动:
private void Delete_Click(object sender, RoutedEventArgs e)
{
var index = CitiesDisplay.SelectedIndex;
if(CitiesDisplay.SelectedIndex >= 0)
{
vm.Cities.Remove(vm.Cities[index]);
}
}
这是我的ListView:
<ListView Name="CitiesDisplay" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Holding="ListViewItem_Holding">
<!-- Begin Flyout menu -->
<FlyoutBase.AttachedFlyout>
<MenuFlyout>
<MenuFlyoutItem Text="Delete" Click="Delete_Click"/>
<MenuFlyoutItem Text="Navigate To" Click="NavigateTo_Click"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
<!-- End Flyout Menu -->
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical">
<TextBlock Name="CityName" Text="{Binding Name}" FontSize="20"></TextBlock>
<TextBlock Name="MaxTemp" Text="{Binding max}"/>
<TextBlock Name="MinTemp" Text="{Binding min}"/>
<TextBlock Name="CurrentTemp" Text="{Binding temp}"/>
</StackPanel>
<Image Name="Logo" Width="50" Height="50" Source="{Binding icon}" HorizontalAlignment="Right" Margin="5"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我真的不明白为什么我无法获得我的SelectedIndex,因为我在之前的项目中做了同样的事情而且它完美无缺。
我也尝试过操纵SelectedItems无济于事。
其他一些细节:我使用Visual Studio 2015 Update 1开发Windows Phone 8.1应用程序(winrt)。
答案 0 :(得分:0)
是的,SelectedIndex
将始终保持为-1,因为ItemClick
Stackpanel&消耗点击事件的设计约束,SelectionChanged
和ItemTemplate
事件都不会触发#39; s Holding
事件
要解决这个问题,你会
VisualTree
遍历到父级
ItemTemplate中您的XAML将保持不变,您的代码将更改为
private DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
{
DependencyObject parent = startObject;
while (parent != null)
{
if (type.IsInstanceOfType(parent))
break;
else
parent = VisualTreeHelper.GetParent(parent);
}
return parent;
}
private void Delete_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
var selectedItem = GetDependencyObjectFromVisualTree(e.OriginalSource as DependencyObject, typeof(ListViewItem)) as ListViewItem;
//here you can use it to traverse your vm.Cities list to update it or do anything.
System.Diagnostics.Debug.WriteLine(((YourModel)selectedItem.Content).Cities);
}