运行 在 Xamarin.forms 中使用计时器更改另一个页面的背景图像的后台进程

Run a background process to change backgroundimage of another page using timer in Xamarin.forms

嗨,Whosebug 团队,

我正在尝试 运行 我的应用程序中的后台进程。这个后台进程应该每 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, 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, 0);
            base.OnAppearing();
        }

您正在创建 HomePage 的实例并尝试更新它,但它与您的 MasterDetail

中显示的实例不同

尝试这样的事情

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

或者,您可以使用 MessagingCenterHomePage 发送消息,请求更新