0
votes

I implemented a custom StackLayout in my Xamarin.Forms project to make the background of a ContentPage a Gradient, and I want to change the gradient flow in the code behind depending on the OS of the device. The problem is that when I assign a value to x:Name I can't find it in the xaml.cs class, therefore I cant access to its properties. Here goes the code:

Custom StackLayout code:

namespace MyProject.Renderers
{
    public class GradientLayout : StackLayout
    {
        public string ColorsList { get; set; }
        public Color[] Colors
        {
            get
            {
                string[] hex = ColorsList.Split(',');
                Color[] colors = new Color[hex.Length];

                for (int i = 0; i < hex.Length; i++)
                {
                    colors[i] = Color.FromHex(hex[i].Trim());
                }

                return colors;
            }
        }

        public GradientColorStackMode Mode { get; set; }
    }
}

xaml code:

<renderers:GradientLayout
        x:Name="theGradient"
        ColorsList="#D81BDE,#4847FF"
        Mode="ToBottomLeft">

        //Irrelevant content

</renderers:GradientLayout>

xaml.cs code:

public partial class LogInPage : ContentPage
    {
        public LogInPage()
        {
            InitializeComponent();

            if (Device.RuntimePlatform == Device.iOS)
            {
                //theGradient do not appear 
            }
        }
    }

And that is it, if you need any more information I will provide it as soon as I see your request, thank you all for your time, have a good day.

1
this should work. For weird XAML issues, try killing VS, deleting all bin/obj folders, restarting VS, and rebuilding - Jason

1 Answers

1
votes

Did you create custom renderer for IOS and Android like this thread? https://stackoverflow.com/a/49862125/10627299

If so, make sure you add the WidthRequest="200" HeightRequest="200" for your GradientLayout

  <renderers:GradientLayout
   ColorsList="#dd8f68,#a9a9a9,#3a3939"
   Mode="ToBottomRight" 
   WidthRequest="200" 
   HeightRequest="200">

 </renderers:GradientLayout>

Here is running screenshot.

enter image description here

If above code is still not worked. You can use Magic Gradients in your applcation https://github.com/mgierlasinski/MagicGradients