微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何根据xamarin.forms中的条件更改条目的线条颜色

如何解决如何根据xamarin.forms中的条件更改条目的线条颜色

enter image description here

因此,我对条目进行了一些验证,当值无效时,我想将颜色更改为红色。

现在有没有办法在xamarin中做到这一点?

我知道有一个渲染器可以永久更改颜色,但是我只想根据条件进行更改,并在一切正常时将其保留为黑色。

谢谢。

解决方法

要更改该行,必须使用自定义渲染器like this

或者只是将行隐藏在自定义渲染器中,然后在页面上伪造一行,然后可以通过Data trigger控制颜色。

或者,添加框架或更改背景颜色(而不是条目)呢?

,

您可以在CustomRenderer中覆盖OnElementPropertyChanged方法以实现此目的。

例如:

对于 Android

[assembly: ExportRenderer(typeof(Entry),typeof(UnderLineEntry))]
namespace EntryCa.Droid
{
  class UnderLineEntry : EntryRenderer
  {
    public UnderLineEntry(Context context) : base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);

        if (Control == null || e.NewElement == null) return;

        Control.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Black);
    }

    protected override void OnElementPropertyChanged(object sender,PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender,e);
        if (e.PropertyName == Entry.TextProperty.PropertyName)
        {
            if (Control.Text.Length > 6)  //this is your condition(For example,here is the length of the text content)
            {
                Control.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Red);
            }
            else
            {
                Control.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Black);
            }
        } 
    }
  }
}

ios与Android相似,如果需要,也可以通过OnElementPropertyChanged方法对其进行更改。

用于 ios

[assembly: ExportRenderer(typeof(Entry),typeof(MyEntryRenderer))]
namespace EntryCa.iOS
{
  public class MyEntryRenderer : EntryRenderer
  {
    private CALayer _line;

   public override void LayoutSubviews()
    {
        base.LayoutSubviews();

        Control.BorderStyle = UITextBorderStyle.None;

        _line = new CALayer
        {
            BackgroundColor = UIColor.Black.CGColor,Frame = new CGRect(0,Frame.Height,Frame.Width,1f)
        };

        Control.Layer.AddSublayer(_line);
    }

    protected override void OnElementPropertyChanged(object sender,e);
        if (e.PropertyName == Entry.TextProperty.PropertyName)
        {
            if (Control.Text.Length > 6)
            {
                _line.RemoveFromSuperLayer();
                _line = new CALayer
                {
                    BackgroundColor = UIColor.Red.CGColor,1f)
                };

                Control.Layer.AddSublayer(_line);
            }
            else
            {
                _line.RemoveFromSuperLayer();
                _line = new CALayer
                {
                    BackgroundColor = UIColor.Black.CGColor,1f)
                };

                Control.Layer.AddSublayer(_line);
            }
        }
    }
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。