你如何在 Xamarin 上创建一个根据平台做不同事情的函数? [英] How do you create on Xamarin a function that does something differently depending on the platform?

查看:28
本文介绍了你如何在 Xamarin 上创建一个根据平台做不同事情的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Xamarin 的新手,我正在开发适用于 Android、iOS 和 UWP 的应用.目前,我想做一些不幸的事情,但不幸的是,从跨平台 Xamarin.forms 调用的 ViewModel 在每个平台上的工作方式都不同.

I'm new to Xamarin and I'm developing an App for Android, iOS and UWP. At the moment I want to do something that unfortunately works differently on every platform from a ViewModel that's called by the crossplatform Xamarin.forms.

如何根据当前构建的平台从运行不同平台特定代码的 ViewModel 创建函数或类?

How do I create a function or class from that ViewModel that runs different Platform specific code depending on the platform that currently build?

推荐答案

有一个名为 DependencyService 的服务,它允许你注册一个接口的多个实现,它会根据当前环境自动返回正确的实现.

There is a service called DependencyService which allows you to register multiple implementations of an interface and it automatically returns proper implementation based on current environment.

您在常用项目中定义接口,例如:

You define interface in your common project, e.g.:

public interface IPrinter
{
    void Print();
}

并且在每个项目中您创建不同的实现.您还必须使用 [assembly(typeof(YOUR_CLASS_NAME))] 属性对其进行标记.

And in each project you create different implementation. You also have to mark it with [assembly(typeof(YOUR_CLASS_NAME))] attribute.

[assembly:Dependency(typeof(AndroidPrinter))]
namespace MyApp.Android
{
    public class AndroidPrinter : IPrinter
    {
        public class Print()
        {
        }
    }
}

然后在你常用的项目中,在ViewModel中,你可以调用:

Then in your common project, in ViewModel, you can call:

public void ViewModelFooMethod()
{
    DependencyService.Get<IPrinter>().Print();
}

更多相关信息这里

这篇关于你如何在 Xamarin 上创建一个根据平台做不同事情的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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