问题
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.
How do I create a function or class from that ViewModel that runs different Platform specific code depending on the platform that currently build?
回答1:
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();
}
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()
{
}
}
}
Then in your common project, in ViewModel, you can call:
public void ViewModelFooMethod()
{
DependencyService.Get<IPrinter>().Print();
}
More about it here
回答2:
This should be your if
else
statement in your ViewModel
class based on Platform
. You can append one more else
block that would be default for UWP
if (Device.RuntimePlatform == Device.iOS)
{
//ios
}
else if (Device.RuntimePlatform == Device.Android)
{
//android
}
One more way is there to get it is by using Xam.Plugin.DeviceInfo package from NuGet Package manager. Import
using Plugin.DeviceInfo;
Get Platform
info like this
CrossDeviceInfo.Current.Platform.ToString();
来源:https://stackoverflow.com/questions/53153603/how-do-you-create-on-xamarin-a-function-that-does-something-differently-dependin