ContextMenu,获取父TextBlock Id

时间:2013-04-12 09:28:04

标签: windows-phone-8 windows-phone

ListBox的ItemSource是一个ObservableCollection of Animals。 每只动物都有一个名字和一个Id。在显示动物名称的TextBlock中,我有一个ContextMenu。长按时,会显示UnFollow菜单。单击该菜单时,它会引发UnFollow_OnClick事件。

现在我的问题是,我怎么能在我的代码背后获得动物的身份?

尝试了一些不同的方案但找不到任何有效的解决方案。

 <ListBox x:Name="AllAnimals" Margin="0,0,-12,0" ItemsSource="{Binding AllAnimals}">
               <ListBox.ItemTemplate>
                  <DataTemplate>
                     <StackPanel Margin="0,0,0,17">
                        <TextBlock Text="{Binding Name}" TextWrapping="NoWrap" Style="{StaticResource PhoneTextExtraLargeStyle}">
                           <toolkit:ContextMenuService.ContextMenu>
                              <toolkit:ContextMenu IsZoomEnabled="False">
                                    <toolkit:MenuItem Header="Unfollow" Click="UnFollow_OnClick" />
                              </toolkit:ContextMenu>
                           </toolkit:ContextMenuService.ContextMenu>
                        </TextBlock>
                     </StackPanel>
                  </DataTemplate>
               </ListBox.ItemTemplate>
            </ListBox>

private void UnFollow_OnClick(object sender, RoutedEventArgs e)
{  

}

2 个答案:

答案 0 :(得分:2)

这应该有效:

    private void UnFollow_OnClick(object sender, RoutedEventArgs e)
    {
        Animal animal = ((Animal)((sender as FrameworkElement).DataContext));

        MenuItem item = (sender as MenuItem);
        string itemValue = item.Header.ToString();

        if (itemValue == "Unfollow")
        {
            try
            {
                if (animal != null)
                {
                    // animal.Id
                }
            }
            catch (Exception)
            {
            }
        }
    }

答案 1 :(得分:0)

试试这个:

 private void UnFollow_OnClick(object sender, RoutedEventArgs e)
    {
        var animal = AllAnimals.SelectedItem as Animal;
        if(animal==null) return;
        var id = animal.Id;
    }

希望得到它的帮助。