Silverlight - How to navigate from a User Control

2019-01-18 04:03发布

If I do this inside a User Control:

NavigationService.Navigate(new Uri("/Alliance.xaml", UriKind.Relative));

it says this error:

An object reference is required for the non-static field, method, or property 'System.Windows.Navigation.NavigationService.Navigate(System.Uri)'

Thank you


Well, I solved passing the normal Page as an argument to the User Control, so I could get the NavigationService.

8条回答
何必那么认真
2楼-- · 2019-01-18 04:08
((Frame)(Application.Current.RootVisual as MainPage).FindName("ContentFrame"))
    .Navigate(new Uri("Page Name", UriKind.Relative));
查看更多
甜甜的少女心
3楼-- · 2019-01-18 04:09

NavigationService is a property of the page object in Silverlight, which is why you are getting this error. It is not a property of a UserControl in Silverlight.

The following are a few options which will be able to solve the issue you're seeing.

  1. Treat the usercontrol as a control. Give it an event which it will fire when the button is clicked. The page can listen for that event and handle the navigation when it fires.

  2. You can either allow your page access to its parent or pass the NavigationService from the page to the usercontrol.

  3. You can also set this up using messaging, but that would be more complicated.Many MVVM frameworks have messaging features. MVVM Light has it.

查看更多
聊天终结者
4楼-- · 2019-01-18 04:15
        if(Application.Current.RootVisual is Page)
        {
            ((Page) (Application.Current.RootVisual)).NavigationService.Navigate(uri);
        }
查看更多
混吃等死
5楼-- · 2019-01-18 04:18
(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(uri);
查看更多
叛逆
6楼-- · 2019-01-18 04:18

Here is another solution for Silverlight for Windows Phone 8:

public Page Page { get; set; }

this.Loaded += delegate
{
    Page = (Application.Current.RootVisual as Frame).Content as Page;
};

Page.NavigationService.Navigate(new Uri("/Alliance.xaml", UriKind.Relative));
查看更多
霸刀☆藐视天下
7楼-- · 2019-01-18 04:21

I normally use an EventHandler. Example: in your user control, define something like

public event EventHandler goToThatPage;

that you will call in your control foe example like this:

goToThatPage(this, new EventArgs());

Then in the constructor of your MainPage.xaml.cs (if the user control is contained there) you will define:

uxControlName.goToThatPage+= new EventHandler(ControlGoToThatPage);

and somewhere in your MainPage.xaml.cs you finaly declare the action to be done:

    void ControlGoToThatPage(object sender, EventArgs e)
    {
        this.NavigationService.Navigate(new Uri("/Pages/ThatPage.xaml", UriKind.Relative));
    }
查看更多
登录 后发表回答