简体   繁体   中英

How to get GridViewItem from its child element?

Suppose I have a code in XAML like this:

<GridView>
  <GridView.ItemTemplate>
<DataTemplate>
    <Button Content="{Binding test}" Click="ButtonClick" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>

Then how can I get which GridViewItem was selected? Because, normally what is done is to add the ItemClick functionality to the GridView itself , but in this case I am doing something customized and need to get the SelectedItem starting from the Button.

I tried code something like this:

void ButtonClick (object sender, RoutedEventArgs e)
{
   var g = (GridViewItem)((Button)sender).Parent;
}

But it does not work (returns null). Please help!

Thanks!

Sure! Here's the code that I use when the ad control fails to load an ad (like when the machine is offline). In that case I remove it form the gridview. To do that I have to locate the ad's parent gridviewitem and remove the whole thing. I do it like this:

private void AdControl_ErrorOccurred_1(object sender, Microsoft.Advertising.WinRT.UI.AdErrorEventArgs e)
{
    var _Item = sender as DependencyObject;
    while (!(_Item is GridViewItem))
        _Item = VisualTreeHelper.GetParent(_Item);
    HubGrid.Items.Remove(_Item);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM