开发者

Pass value from another page to MainPage.xaml in Silverlight when using Navigation?

I have a Page in Silverlight which is Navigated from the MainPage.xaml, called OpenPage.xaml, I then want to pass a value back to the MainPage.xaml - this OpenPage.xaml is called using this:

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

From the mainpage - this is not a child of the MainPage as the RootVisual is replaced - I can call this:

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

To return to the MainPage - however I need to pass a value from OpenPage.xaml to the MainPage.xaml - how to I access the MainPage instance - I have a Property called Document however when I do this:

        MainPage m = (MainPage)Application.Current.RootVisual;
       开发者_如何学编程 m.Document = "Hello World";

Or this:

((MainPage)root).Document = "Hello World";

I get an invalid cast exception because I think it is trying to cast the OpenPage.xaml to MainPage.xaml - how to I get the NavigatedTo Page, I want to set the property on MainPage.xaml from OpenPage.xaml.

I also want to pass values from the MainPage.xaml to another page SavePage.xaml - but this has the same issue - how do I resolve this?


Use a query string value:-

NavigationService.Navigate(new Uri("/MainPage.xaml?value=Hello%20World", UriKind.Relative);

MainPage can then acquire this value using:-

string value =  this.NavigationContext.QueryString["value"];

Edit:

In response to comment re passing other types.

Once you have the above inplace you can use other service patterns to pass other types. For example consider a MessageService that implements:-

interface IMessageService
{
    Guid Store(object value)
    object Retrieve(Guid key)
}

You would then implement this interface and expose the implementation as singleton say:-

public class MessageService : IMessageService
{
    public static IMessageService Default { // singleton stuff here }
}

Your OpenPage calls MessageService.Default.Store and places the resulting Guid in the query string.

The MainPage then tests for the presence of such a query string value, if present uses its value to call MessageService.Default.Retrieve which removes the item from the service.


Partial Public Class MainPage
    Inherits UserControl

    Public Sub New()

        InitializeComponent()

        ContentFrame.Source = New Uri("/About", UriKind.Relative)

        ...............
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜