Write device platform specific code in Xamarin.Forms

前端 未结 5 1502
野性不改
野性不改 2020-12-07 18:57

I have the following Xamarin.Forms.ContentPage class structure

public class MyPage : ContentPage
{
    public MyPage()
    {
        //do work t         


        
5条回答
  •  猫巷女王i
    2020-12-07 19:46

    There are multiple answers, depending on what you want to achieve, and the kind of project you have:

    Execute different Xamarin.Forms code on different platforms.
    Use this e.g. if you want different font sizes on different platforms:

    label.Font = Device.OnPlatform (12, 14, 14);
    

    Execute platform specific code in a shared (PCL) project The common pattern is to use DI (dependency injection) for this. Xamarin.Forms provides a simple DependencyService for this, but use whatever you want.

    Execute platform specific code in shared (Shared Asset Project) project As the code is compiled per platform, you can wrap your platform specific code in #if __PLATFORM__ #endif and have all the code in the same file. The platform project should define __IOS__, __ANDROID__ and __WINDOWS_PHONE__. Note that a shared asset project containing Xaml and code won't work well for iOS on Xamarin.Studio, and that having compiler directives makes your code harder to read and to test.

提交回复
热议问题