Tuesday, August 17, 2010

Code: Silverlight Navigation from a UserControl

For some reason Silverlight does not provide the ability to access a page's NavigationService from a user control, so in order to navigate correctly you have to manually walk the control tree. See the method below to use as a helper class.

public static class NavigationHelper
    {
        public static void Navigate(Uri url, UserControl control)
        {
            Page pg = GetDependencyObjectFromVisualTree(control, typeof(Page)) as Page;
            pg.NavigationService.Navigate(url);
        }

        private static DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
        {
            //Walk the visual tree to get the parent(ItemsControl)
            //of this control
            DependencyObject parent = startObject;
            while (parent != null)
            {
                if (type.IsInstanceOfType(parent))
                    break;
                else
                    parent = VisualTreeHelper.GetParent(parent);
            }
            return parent;
        }
    }