Silverlight NavigationService is always null

I read that several people had a problem with this, so I wanted to post an (somewhat) elegant solution that I came up with when trying to deal with this. The problem is that you are creating template pages in Silverlight, and ContentControls do not have a parent Frame NavigationService (it is always null when you try to use it). There are similar scenarios when a NavigationService is present in intellisence but is always null. To enable navigation throughout the site:

  • Create a new one UserControl(I named my “NavFrame”), which has a navigation frame (I named my “RootFrame”).

  • Inside this frame, you can install any content that you like.

  • Set this UserControl as yours RootVisualin App.xaml.cs (i.e. this.RootVisual = new NavFrame();).

  • To use the NavigationService on any of your pages, you can enter something like:

    ((NavFrame)App.Current.RootVisual).RootFrame.NavigationService
        .Navigate(new Uri("Your Uri", UriKind.RelativeOrAbsolute));
    
+3
source share
2 answers

You can create an Action and drag it on top of the control you want to do, how it happens:

public class NavigateAction : TriggerAction<DependencyObject>
{
    public Uri Uri
    {
        get;
        set;
    }

    protected override void Invoke(object parameter)
    {
        var frame = FindContainingFrame(AssociatedObject);

        if(frame == null)
            throw new InvalidOperationException("Could not find the containing Frame in the visual tree.");

        frame.Navigate(Uri);
    }

    protected static Frame FindContainingFrame(DependencyObject associatedObject)
    {
        var current = associatedObject;

        while(!(current is Frame))
        {
            current = VisualTreeHelper.GetParent(current);

            if(current == null)
                return null;
        }

        return (Frame)current;
    }
}

Now you just need to drag it and connect to the landing page. By the way, this is true for SL4, never tried on SL3. and the URI works in the form: " /SilverlightApplication1;component/Page1.xaml " or with UriMapping in the frame.

+1
source
((Frame)(Application.Current.RootVisual as MainPage).FindName("ContentFrame"))
    .Navigate(new Uri("Page Name", UriKind.Relative));
0
source

Source: https://habr.com/ru/post/1742785/


All Articles