pjrki
pjrki

Reputation: 248

Custom generic OnPlatform in Xamarin forms Issue

I'm developing multiplatform app for an Android, iOS, WinPhone and UWP. I've wrote custom generic OnPlatform class to achieve changing TextColor for specific platforms. The standrd 'OnPlatform' in XAML has only iOS, Android and WinPhone. What i've needed was UWP (see code below)

public class OnPlatformExt<T> : OnPlatform<T>
    {
        public T Android { get; set; }
        public T iOS { get; set; }
        public T WinPhone { get; set; }
        public T Windows { get; set; }
        public T Other { get; set; }

        public OnPlatformExt()
        {
            Android = default(T);
            iOS = default(T);
            WinPhone = default(T);
            Windows = default(T);
            Other = default(T);
        }

        public static implicit operator T(OnPlatformExt<T> onPlatform)
        {
            switch (Xamarin.Forms.Device.OS)
            {
                case Xamarin.Forms.TargetPlatform.Android:
                    return onPlatform.Android;

                case Xamarin.Forms.TargetPlatform.iOS:
                    return onPlatform.iOS;

                case Xamarin.Forms.TargetPlatform.WinPhone:
                    return onPlatform.WinPhone;

                case Xamarin.Forms.TargetPlatform.Windows:
                    return onPlatform.Windows;

                default:
                    return onPlatform.Other;
            }
        }
    }

Then assembly in App.xaml and use in my resource dictionary as

<local:OnPlatformExt x:TypeArguments="Color"
                iOS="#f0f8ff"
                Android="White"
                WinPhone="#008566"
                Windows="White"
                Other="White" x:Key="LightTextColor" />

Everything's compiling well. But this still does not changin this particular color for my buttons style. I wanted to say that when I'm using a normal proper 'OnPlatform x:TypeArguments="Color" ... then it changin colors at particular platforms. Do you guys have any idea what's wrong with this chunk of code?

Upvotes: 1

Views: 605

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32785

I have checked your code and found nothing wrong. I just changed the color ( see codes below) you set,and then I referenced the resource dictionary in the MainPage.xaml like this BackgroundColor="{StaticResource Key=LightTextColor}". And it is working fine in (Xamarin.UWP & Xamarin.Android). Could you please try uninstall the app in your machine, clean the solution and redeploy it? If it doesn’t work. Please have a try of my demo :GitHub.

<ResourceDictionary>
    <local:OnPlatformExt
        x:Key="LightTextColor"
        x:TypeArguments="Color"
        Android="Red"
        Other="White"
        WinPhone="White"
        Windows="#008566"
        iOS="#f0f8ff" />
</ResourceDictionary>

Upvotes: 2

Related Questions