运行后台进程以使用Xamarin.forms中的计时器更改另一个页面的backgroundimage

问题描述

StackOverflow小组敬上

我正在尝试在我的应用程序中运行后台进程。此后台进程应每15秒更新一次应用程序页面中的“背景图片”。到目前为止,我尝试在App OnStart()方法中创建一个计时器,并在BeginInvokeOnMainThread()方法中更新页面的背景图像,但没有成功。有人可以帮我吗?

我的代码-

    {

        private static Stopwatch stopWatch = new Stopwatch();
        private const int defaultTimespan = 20;
        private readonly HomePage homePage;

        public App()
        {
            InitializeComponent();

            try
            {

                MainPage = new MainPage();

                homePage = new HomePage();

            }
            catch(Exception ex)
            {
                string str = ex.Message;
            }
        }

        protected override void OnStart()
        {
            if (!stopWatch.IsRunning)
            {
                stopWatch.Start();
            }

            Device.StartTimer(new TimeSpan(0,10),() =>
            {
                // Logic for logging out if the device is inactive for a period of time.

                if (stopWatch.IsRunning && stopWatch.Elapsed.Seconds >= defaultTimespan)
                {
                    //prepare to perform your data pull here as we have hit the 1 minute mark   

                    // Perform your long running operations here.

                    Device.BeginInvokeOnMainThread(() =>
                    {
                        // If you need to do anything with your UI,you need to wrap it in this.
                        //  homePage.BackgroundImageSource = "goldengate.jpg";
                        homePage.ChangeBackgroundImage();

                    });

                    stopWatch.Restart();
                }

              //  Always return true as to keep our device timer running.
                return true;
            });
        }

        protected override void OnSleep()
        {
            //stopWatch.Reset();
        }

        protected override void OnResume()
        {
            //stopWatch.Start();
        }
        //void ChangeHomePageImage()
        //{
        //    Navigation.PushAsync(new HomePage(appBackground));
        //    Navigation.RemovePage(this);
        //}


    }

MainPage - 
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             xmlns:local="clr-namespace:Excercise.Views"
             x:Class="Excercise.MainPage" IsPresented="False">

    <MasterDetailPage.Master>


        <local:MenuPage x:Name="menuPage"></local:MenuPage>


    </MasterDetailPage.Master>

    <MasterDetailPage.Detail>
        <NavigationPage>
            <x:Arguments>
        <local:HomePage x:Name="homePage"></local:HomePage>
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Detail>
</MasterDetailPage>

HomePage - 
 public partial class HomePage : ContentPage
    {
        private sqliteAsyncConnection _connection;
        
        public HomePage()
        {
            InitializeComponent();
            //  BindingContext = new HomePageviewmodel();
            _connection = DependencyService.Get<IsqliteDb>().GetConnection();
            loadData("");
        }

        public HomePage(string BackgroundimgPath)
        {
            InitializeComponent();
            //  BindingContext = new HomePageviewmodel();
            _connection = DependencyService.Get<IsqliteDb>().GetConnection();
            loadData(BackgroundimgPath);
        }
        public HomePage(string City,string LocationKey,string StateID)
        {
            InitializeComponent();
            _connection = DependencyService.Get<IsqliteDb>().GetConnection();
            // BindingContext = new HomePageviewmodel();
            try
            {
                // Method Calls
            }
            catch (Exception)
            {
                 displayAlert("Error","There was an error loading this page.","OK");
            }
        }

        protected override void OnAppearing()
        {
            this.Title = App.AppTitle;           
            this.firstStacklayout.Margin = new Thickness(0,(Application.Current.MainPage.Height * 0.25),0);
            base.OnAppearing();
        }

解决方法

您正在创建HomePage的实例并尝试对其进行更新,但是它与MasterDetail中显示的实例不同

尝试这样的事情

var md = (MasterDetailPage)MainPage;
var nav = (NavigationPage)md.DetailPage;
var home = (HomePage)nav.CurrentPage;
home.ChangeBackgroundImage();

或者,您可以使用MessagingCenterHomePage发送一条消息,要求其更新