如何从后台任务更新UI?超人

时间:2019-05-29 16:14:13

标签: c# visual-studio xaml background-process

有关应用程序的详细信息:

  • 在Visual Studio 2019(Windows 10)下开发
  • 使用UWPC#语言在XAML平台上设计

文件树:

PROJECT UI:    - 主页    -CallSection

项目背景:    -ActivityTask

MainPage.xaml.cs包含一个框架CallsSection,该框架包含CallSection.xaml.cs文件,位于下面的XAML:(MainPage.xaml)

<Page
    x:Class="PhonieMartha.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PhonieMartha"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Frame x:Name="CallsSection" Grid.Column="1"/>
/>

从后台任务接收到数据后,OnCompleted事件将在MainPage.xaml.cs上执行

代码:(MainPage.xaml.cs)

private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
    ushort ID_MESSAGE = 800;
    UpdateUI(ID_MESSAGE);
}

public void UpdateUI(ushort ID_MESSAGE)
{
    MainPage mainPage = FindParent<MainPage>(this);
    if (mainPage != null)
    {
        CallSection cellSection = mainPage.CallsSection.Content as CallSection;
        if (cellSection != null)
        {
            Debug.WriteLine("WORK");
        }
        else
        {
            Debug.WriteLine("CallSection FAIL");
        }        
    }
    else
    {
        Debug.WriteLine("MainPage FAIL");
    }
}

private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);

    if (parent == null) return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}

我得到的结果是:MainPage FAIL

我无法获取CallsSection框架的全部内容,因此无法更改此框架的UI。

我也对此进行了测试:

await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => 
{

});

但是没有任何作用,我该如何解决?

0 个答案:

没有答案