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

如何以编程方式在 Xamarin Forms 输入字段上触发 TextChanged 事件? 文档回购示例

如何解决如何以编程方式在 Xamarin Forms 输入字段上触发 TextChanged 事件? 文档回购示例

我们为非空输入字段等设置了一些 Xamarin 行为,当用户更改字段时触发,然后我们更改了输入边框颜色,红色表示无效。

但是,我们还希望在点击提交按钮时重用此行为。

所以我需要手动触发 TextChanged 事件,任何想法如何做到这一点,现在确定是否可能?

public class NotEmptyEntryBehavIoUr : Behavior<Entry>
{
    protected override void OnAttachedTo(Entry bindable)
    {
        bindable.TextChanged += OnEntryTextChanged;
        base.OnAttachedTo(bindable);
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= OnEntryTextChanged;
        base.OnDetachingFrom(bindable);
    }

    void OnEntryTextChanged(object sender,TextChangedEventArgs args)
    {
        if (args == null)
            return;

        var oldString = args.OldTextValue;
        var newString = args.NewTextValue;
    }
}

解决方法

如果您想要替代方案,您可以使用 Xamarin.CommunityToolkit package 附带的预构建验证行为之一,例如 TextValidationBehavior(通过指定 Regexp)或任何更具体的派生行为(例如 {{ 1}}) 可以满足您的需求,甚至可以通过子类化 ValidationBehavior 来创建自定义。

它允许您为 Valid 和 InValid 状态定义自定义样式,但对问题更重要的是有一个名为 NumericValidationBehavior 的异步方法。

还有 Flags 属性可能很有趣。

ForceValidate() 似乎更接近于 NotEmptyEntryBehaviourTextValidationBehavior

xaml

MinimumLenght=1

代码

 <Entry Placeholder="Type something..." x:Name="entry">
        <Entry.Behaviors>
            <xct:TextValidationBehavior Flags="ValidateOnValueChanging"
                                        InvalidStyle="{StaticResource InvalidEntryStyle}"
                                        ValidStyle="{StaticResource ValidEntryStyle}"/>
        </Entry.Behaviors>
    </Entry>

文档

https://docs.microsoft.com/en-us/xamarin/community-toolkit/behaviors/charactersvalidationbehavior

回购示例

https://github.com/xamarin/XamarinCommunityToolkit/tree/main/samples/XCT.Sample/Pages/Behaviors

,

我们为非空输入字段等设置了一些 Xamarin 行为,当用户更改字段时触发,然后我们更改了输入边框颜色,红色表示无效。

您可以使用要获取的行为创建自定义条目。

我要做的第一件事是创建一个继承自 Entry 的新控件,并将添加三个属性:IsBorderErrorVisible、BorderErrorColor、ErrorText。

public class ExtendedEntry : Entry
{
    public static readonly BindableProperty IsBorderErrorVisibleProperty =
        BindableProperty.Create(nameof(IsBorderErrorVisible),typeof(bool),typeof(ExtendedEntry),false,BindingMode.TwoWay);

    public bool IsBorderErrorVisible
    {
        get { return (bool)GetValue(IsBorderErrorVisibleProperty); }
        set
        {
            SetValue(IsBorderErrorVisibleProperty,value);
        }
    }

    public static readonly BindableProperty BorderErrorColorProperty =
        BindableProperty.Create(nameof(BorderErrorColor),typeof(Xamarin.Forms.Color),Xamarin.Forms.Color.Transparent,BindingMode.TwoWay);

    public Xamarin.Forms.Color BorderErrorColor
    {
        get { return (Xamarin.Forms.Color)GetValue(BorderErrorColorProperty); }
        set
        {
            SetValue(BorderErrorColorProperty,value);
        }
    }

    public static readonly BindableProperty ErrorTextProperty =
    BindableProperty.Create(nameof(ErrorText),typeof(string),string.Empty);

    public string ErrorText
    {
        get { return (string)GetValue(ErrorTextProperty); }
        set
        {
            SetValue(ErrorTextProperty,value);
        }
    }
}

然后创建自定义渲染到 android 平台。

[assembly: ExportRenderer(typeof(ExtendedEntry),typeof(ExtendedEntryRenderer))]
namespace FormsSample.Droid
{
public class ExtendedEntryRenderer : EntryRenderer
{
    public ExtendedEntryRenderer(Context context) : base(context)
    {
    }
    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);

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

        UpdateBorders();
    }

    protected override void OnElementPropertyChanged(object sender,System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender,e);

        if (Control == null) return;

        if (e.PropertyName == ExtendedEntry.IsBorderErrorVisibleProperty.PropertyName)
            UpdateBorders();
    }

    void UpdateBorders()
    {
        GradientDrawable shape = new GradientDrawable();
        shape.SetShape(ShapeType.Rectangle);
        shape.SetCornerRadius(0);

        if (((ExtendedEntry)this.Element).IsBorderErrorVisible)
        {
            shape.SetStroke(3,((ExtendedEntry)this.Element).BorderErrorColor.ToAndroid());
        }
        else
        {
            shape.SetStroke(3,Android.Graphics.Color.LightGray);
            this.Control.SetBackground(shape);
        }

        this.Control.SetBackground(shape);
    }

}

}

最后,Creating an Entry Behavior,处理错误,在验证发生时向用户提供ui反馈

 public class EmptyEntryValidatorBehavior : Behavior<ExtendedEntry>
{
    ExtendedEntry control;
    string _placeHolder;
    Xamarin.Forms.Color _placeHolderColor;

    protected override void OnAttachedTo(ExtendedEntry bindable)
    {
        bindable.TextChanged += HandleTextChanged;
        bindable.PropertyChanged += OnPropertyChanged;
        control = bindable;
        _placeHolder = bindable.Placeholder;
        _placeHolderColor = bindable.PlaceholderColor;
    }

    void HandleTextChanged(object sender,TextChangedEventArgs e)
    {
        ExtendedEntry customentry = (ExtendedEntry)sender;
        if (!string.IsNullOrEmpty(customentry.Text))
        {
            ((ExtendedEntry)sender).IsBorderErrorVisible = false;
        }
        else
        {
            ((ExtendedEntry)sender).IsBorderErrorVisible = true;
        }
      
    }

    protected override void OnDetachingFrom(ExtendedEntry bindable)
    {
        bindable.TextChanged -= HandleTextChanged;
        bindable.PropertyChanged -= OnPropertyChanged;
    }

    void OnPropertyChanged(object sender,System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == ExtendedEntry.IsBorderErrorVisibleProperty.PropertyName && control != null)
        {
            if (control.IsBorderErrorVisible)
            {
                control.Placeholder = control.ErrorText;
                control.PlaceholderColor = control.BorderErrorColor;
                control.Text = string.Empty;
            }

            else
            {
                control.Placeholder = _placeHolder;
                control.PlaceholderColor = _placeHolderColor;
            }

        }
    }
}

enter image description here

更新:

您可以在 button.click 中更改自定义条目的 IsBorderErrorVisible,以从提交按钮调用它。

 private void btn1_Clicked(object sender,EventArgs e)
    {
       
        if(string.IsNullOrEmpty(entry1.Text))
        {
            entry1.IsBorderErrorVisible = true;
        }
    }

<customentry:ExtendedEntry
            x:Name="entry1"
            BorderErrorColor="Red"
            ErrorText="please enter name!">
            <customentry:ExtendedEntry.Behaviors>
                <behaviors:EmptyEntryValidatorBehavior />
            </customentry:ExtendedEntry.Behaviors>
        </customentry:ExtendedEntry>

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