C# 在后台线程中获取当前显示的页面

C# 在后台线程中获取当前显示的页面,c#,windows-phone-8,C#,Windows Phone 8,我有一个后台线程通过计时器事件周期性地运行。我知道如何对UI线程调用一些东西: Deployment.Current.Dispatcher.BeginInvoke( () => { // doing stuff here... f_Foo("hello world"); }); 如何在后台线程中解析当前向用户显示的页面?出于某些原因,我需要在我的f_Foo中引用当前页面,如下所示: f_Foo(this, "hello world"); 但是这个不起作用。这是我的福福

我有一个后台线程通过计时器事件周期性地运行。我知道如何对UI线程调用一些东西:

Deployment.Current.Dispatcher.BeginInvoke( () => { 
    // doing stuff here...
    f_Foo("hello world");
});
如何在后台线程中解析当前向用户显示的页面?出于某些原因,我需要在我的f_Foo中引用当前页面,如下所示:

f_Foo(this, "hello world");
但是
这个
不起作用。这是我的福福宣言:

public static void f_Foo(PhoneApplicationPage pPage, string pMessage) { ... }

为了实现这一点,如果您使用
NavigationService.CurrentSource
,它将返回在给定时间向用户显示的页面的当前Uri

如果需要访问页面实例,请声明PhoneApplicationPage类型的静态全局变量(例如在App.xaml.cs文件中)

然后,在页面的每个OnNavigatedTo方法上,将当前页面分配给该变量

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        Application.Current.CurrentPage = this;
        base.OnNavigatedTo(e);
    }
然后,您可以在方法中调用:

    f_Foo(Application.Current.CurrentPage, "hello world");

为了实现这一点,如果您使用
NavigationService.CurrentSource
,它将返回在给定时间向用户显示的页面的当前Uri

如果需要访问页面实例,请声明PhoneApplicationPage类型的静态全局变量(例如在App.xaml.cs文件中)

然后,在页面的每个OnNavigatedTo方法上,将当前页面分配给该变量

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        Application.Current.CurrentPage = this;
        base.OnNavigatedTo(e);
    }
然后,您可以在方法中调用:

    f_Foo(Application.Current.CurrentPage, "hello world");

下面是一个返回当前显示页面的方法:

public static Page GetCurrentPage() {
    Page page;
    if (Application.Current.RootVisual is Page) {
        page = (Page)Application.Current.RootVisual;
    } else if (Application.Current.RootVisual is Frame) {
        var frame = (Frame)Application.Current.RootVisual;
        page = (Page)frame.Content;
    } else {
        page = null;
    }
    return page;
}

只需更改代码或将结果强制转换为PhoneApplicationPage。哦,您只能从UI线程调用它,但在您的情况下(或在我看到的任何其他情况下),这应该不是问题。

下面是一个返回当前显示页面的方法:

public static Page GetCurrentPage() {
    Page page;
    if (Application.Current.RootVisual is Page) {
        page = (Page)Application.Current.RootVisual;
    } else if (Application.Current.RootVisual is Frame) {
        var frame = (Frame)Application.Current.RootVisual;
        page = (Page)frame.Content;
    } else {
        page = null;
    }
    return page;
}

只需更改代码或将结果强制转换为PhoneApplicationPage。哦,您只能从UI线程调用它,但在您的情况下(或在我见过的任何其他情况下),这应该不是问题。

不。我不需要Uri,我需要对象。只需编辑答案即可显示对象@亚森的回答似乎也相当不错。我不需要Uri,我需要对象。只需编辑答案以显示对象@亚森的回答似乎也相当不错。