Showing posts with label FindAncestor. Show all posts
Showing posts with label FindAncestor. Show all posts

Wednesday, March 19, 2014

Windows Phone FindAncestor Control XAML

Now that my app is progressing along I have a proliferation of xaml elements on each of my screens.
I ran into the issue during an event I have the child element but I needed a reference to the parent element.  APIs exist to really ease this process.  Using the VisualTreeHelper I was able to walk the tree with this routine which I discovered in the stackoverflow forum.


XAML:
<DataTemplate x:Key="SimpleItemTemplate">
  <Button Click="Button_Click">In DataTemplate</Button>
</DataTemplate>
Code behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
  Button btn = (Button)sender;
  ListBox lb = FindAncestor<ListBox>(btn);
  Debug.WriteLine(lb);
}

public static T FindAncestor<T>(DependencyObject from)
  where T : class
{
  if (from == null)
  {
    return null;
  }

  T candidate = from as T;
  if (candidate != null)
  {
    return candidate;
  }

  return FindAncestor<T>(VisualTreeHelper.GetParent(from));
}


source:
http://stackoverflow.com/questions/2633109/listboxitem-parent-returns-nothing-unable-to-get-it-thru-visualtreehelper-getpa
http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper.getparent(v=vs.95).aspx