Xamarin.Forms 如何从另一个 CS 文件访问公共函数? [英] Xamarin.Forms how do I access a public function from another CS file?

查看:22
本文介绍了Xamarin.Forms 如何从另一个 CS 文件访问公共函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是 XF 的新手,我想知道 Android 上的 AppState/Activity 生命周期.其正下方的代码位于名为 test.xaml.cs 的文件中.

So I'm new to XF and I'm wondering about AppState/Activity life cycle on Android. The code directly below this is in a file called test.xaml.cs.

声音的工作原理是您可以说诸如 startSound.Play()startSound.Stop() 之类的内容来启动或停止应用程序中的声音.我注意到一个错误,当应用程序的其余部分通过后退按钮重置时,它不会停止声音(即使它保存在内存中?)

How the sound works is you can say something like startSound.Play() or startSound.Stop() to start or stop sound in the app. I have noticed a bug that doesn't stop sound when the rest of the app resets via the back button (even though it's held in memory?)

public Test()
    {
        startSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
        startSound.Load(Path.Combine($"Audio", "startBeep.wav"));

        stopSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
        stopSound.Load(Path.Combine($"Audio", "stopBeep.wav"));

        winSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
        winSound.Load(Path.Combine($"Audio", "winBeep.wav"));

        endSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
        endSound.Load(Path.Combine($"Audio", "endBeep.wav"));

        addSound = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
        addSound.Load(Path.Combine($"Audio", "addBeep.wav"));
    }

我想做的是在 app.xaml.cs 文件中进入受保护的 override void OnSleep() 并编写 startSound.stop(); 以便在应用程序休眠时声音停止.但是我不知道如何访问test.xaml.csTest的公共函数.

What I would like to do is in the app.xaml.cs file to go into protected override void OnSleep() and write startSound.stop(); so that the sound stops whenever the app sleeps. However I do not know how to access the public function of Test in test.xaml.cs.

这是app.xaml.cs

protected override void OnSleep()
    {
        Debug.WriteLine("OnSleep");
        // Handle when your app sleeps
    }

我使用调试来确保应用状态发生变化,因此我知道 OnSleep() 正常工作.

I've used the debug to make sure that the app state changes so I know the OnSleep() works properly.

推荐答案

您可以使用 MessagingCenter 来实现这一点.

You can use MessagingCenter to accomplish that.

Xamarin.Forms MessagingCenter 使视图模型和其他组件能够进行通信,除了简单的消息合同之外,无需了解彼此的任何信息.

Xamarin.Forms MessagingCenter enables view models and other components to communicate with without having to know anything about each other besides a simple Message contract.

只需在您的 AppOnSleep 中发送一条消息,然后在您的 Test 上订阅该消息:

Just send a message in the OnSleep of your App and subscribe to the message on your Test:

在您的 OnSleep 中:

In your OnSleep:

MessagingCenter.Send<App>(this, "OnSleep");

在您的测试中:

MessagingCenter.Subscribe<App>(this, "OnSleep", (sender) => {
    startSound.stop(); 
});

这篇关于Xamarin.Forms 如何从另一个 CS 文件访问公共函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆