Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 标识已通过事件处理程序点击的ItemsControl项的索引/行号_C#_Xaml_Windows Phone 8_Windows Phone_Itemscontrol - Fatal编程技术网

C# 标识已通过事件处理程序点击的ItemsControl项的索引/行号

C# 标识已通过事件处理程序点击的ItemsControl项的索引/行号,c#,xaml,windows-phone-8,windows-phone,itemscontrol,C#,Xaml,Windows Phone 8,Windows Phone,Itemscontrol,我有一个用户保存的位置列表,供将来参考(这是一个天气应用程序) 我正在使用ItemsControl显示列表: <ItemsControl Grid.Row="0" x:Name="locations" ItemsSource="{Binding Path=Locations}" ItemTemplate="{StaticResource

我有一个用户保存的位置列表,供将来参考(这是一个天气应用程序)

我正在使用ItemsControl显示列表:

            <ItemsControl 
                Grid.Row="0"
                x:Name="locations"
                ItemsSource="{Binding Path=Locations}"
                ItemTemplate="{StaticResource locationRow}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Vertical" />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
我成功地获得了我想要的索引,但是将第二行简单地更改为:

int index = this.viewModel.Locations.IndexOf(sourceObject);

所以我得到了我想要的解决方案,但仍然很好奇为什么最初的建议1)不起作用,2)是推荐的解决方案,而不是仅仅使用sourceObject作为参数值(我相信这是有充分的理由的!)。

您无法通过索引找到UIElement(点击项)。您的
ItemsPanel
是不支持索引的StackPanel。相反,您可以在
ItemsSource
中获取点击项的DataContext及其索引,并使用该对象

private void TextBlock_OnTap(object sender, GestureEventArgs e)
{
    var sourceObject = ((FrameworkElement) sender).DataContext as TypeOfLocation;
    int index = ViewModel.Locations.IndexOf(item => item.City == sourceObject.City);
}
为了在视图中获取ViewModel的实例,可以在代码隐藏类中设置ViewModel的公共属性

public MyViewModel ViewModel
{  
    get { return (MyViewModel) this.DataContext; }
}

好的,您的列表中有任何类型的主键吗?没有,但我认为城市名称是唯一的。好的,将主键分开,您希望在各自的文本块上获取国家和城市名称吗?1)您是否使用System.Linq?对于2)这里不需要第一行,即获取发送方的datacontext。如果每个位置都是唯一的,则可以直接在Locations集合中搜索源对象索引。请标记正确答案。我遇到以下错误:无法将lambda表达式转换为类型“MetroApp.LocationDbRecord”,因为它不是委托类型。LocationDbRecord是sourceObject的类型,是一个Db表,即:“[table]公共类LocationDbRecord:ObserveObject”有什么想法吗?
private void TextBlock_OnTap(object sender, GestureEventArgs e)
{
    var sourceObject = ((FrameworkElement) sender).DataContext as TypeOfLocation;
    int index = ViewModel.Locations.IndexOf(item => item.City == sourceObject.City);
}
public MyViewModel ViewModel
{  
    get { return (MyViewModel) this.DataContext; }
}