簡體   English   中英

使用導航時將值從另一個頁面傳遞到Silverlight中的MainPage.xaml?

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

我在Silverlight中有一個從MainPage.xaml導航的頁面,稱為OpenPage.xaml,然后我想將值傳遞回MainPage.xaml-使用以下命令調用此OpenPage.xaml:

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

從主頁上-這不是MainPage的子級,因為RootVisual被替換了-我可以這樣稱呼:

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

要返回MainPage-但是,我需要將一個值從OpenPage.xaml傳遞給MainPage.xaml-如何訪問MainPage實例-但是,當我執行此操作時,我有一個名為Document的屬性:

        MainPage m = (MainPage)Application.Current.RootVisual;
        m.Document = "Hello World";

或這個:

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

我收到無效的強制轉換異常,因為我認為它正在嘗試將OpenPage.xaml轉換為MainPage.xaml-如何獲取NavigatedTo頁面,我想從OpenPage.xaml設置MainPage.xaml上的屬性。
我也想將值從MainPage.xaml傳遞到另一個頁面SavePage.xaml-但這有相同的問題-我該如何解決?

使用查詢字符串值:

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

MainPage然后可以使用以下方法獲取此值:

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

編輯

為了回應評論,重新傳遞其他類型。

一旦有了上述內容,就可以使用其他服務模式來傳遞其他類型。 例如,考慮一個實現以下內容的MessageService:

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

然后,您將實現此接口並將實現公開為單例說:

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

您的OpenPage調用MessageService.Default.Store並將生成的Guid放在查詢字符串中。

然后,MainPage將測試是否存在這樣的查詢字符串值,如果存在,則使用其值來調用MessageService.Default.Retrieve ,后者將從服務中刪除該項目。

Partial Public Class MainPage
    Inherits UserControl

    Public Sub New()

        InitializeComponent()

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

        ...............

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM