【问题标题】:How to access a custom StackLayout from CodeBehind in Xamarin.Forms?如何从 Xamarin.Forms 中的 CodeBehind 访问自定义 StackLayout?
【发布时间】:2020-03-01 20:45:26
【问题描述】:

我在我的 Xamarin.Forms 项目中实现了一个自定义 StackLayout,以使 ContentPage 的背景成为渐变,并且我想根据设备的操作系统更改后面代码中的渐变流。问题是当我为 x:Name 赋值时,我在 xaml.cs 类中找不到它,因此我无法访问它的属性。代码如下:

自定义 StackLayout 代码:

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; }
    }
}

xml代码:

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

        //Irrelevant content

</renderers:GradientLayout>

xaml.cs 代码:

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

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

就是这样,如果您需要更多信息,我会在看到您的请求后立即提供,谢谢大家的时间,祝您有美好的一天。

【问题讨论】:

  • 这应该可以。对于奇怪的 XAML 问题,尝试杀死 VS,删除所有 bin/obj 文件夹,重新启动 VS,然后重建

标签: c# visual-studio xaml xamarin xamarin.forms


【解决方案1】:

您是否像这个线程一样为 IOS 和 Android 创建了自定义渲染器? https://stackoverflow.com/a/49862125/10627299

如果是这样,请确保为您的GradientLayout 添加WidthRequest="200" HeightRequest="200"

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

 </renderers:GradientLayout>

这是运行截图。

如果上面的代码仍然不起作用。您可以在您的应用程序中使用Magic Gradients https://github.com/mgierlasinski/MagicGradients

【讨论】:

  • 我添加了 widthRequest 和 HeightRequest ,正如你所说,它现在正在工作,非常感谢。如果问的不是太多,并且如果您有空闲时间,请向我解释为这些属性赋予值有什么不同。祝你有美好的一天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多