【问题标题】:Xamarin.Forms How to add Behaviors in codeXamarin.Forms 如何在代码中添加行为
【发布时间】:2015-08-06 21:58:12
【问题描述】:

我想要实现的是通过代码而不是 XAML 将 Entry 字段的输入限制为两个字符

这可以通过以下方式在 XAML 中实现:

<Entry.Behaviors>
        <local:NumberValidatorBehavior x:Name="ageValidator" />
        <local:MaxLengthValidator  MaxLength="2"/>

我假设我需要做这样的事情,但我不太确定如何添加所需的行为属性

entry.Behaviors.Add(new MyBehavior())

编辑答案

添加下面列出的 MaxLengthValidator 类并使用@Rui Marinho 建议的方法调用它后,我的代码按预期工作。

public class MaxLengthValidator : Behavior<Entry>
{
    public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidator), 0);

    public int MaxLength
    {
        get { return (int)GetValue(MaxLengthProperty); }
        set { SetValue(MaxLengthProperty, value); }
    }

    protected override void OnAttachedTo(Entry bindable)
    {
        bindable.TextChanged += bindable_TextChanged;
    }

    private void bindable_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (e.NewTextValue.Length > 0 && e.NewTextValue.Length > MaxLength)
            ((Entry)sender).Text = e.NewTextValue.Substring(0, MaxLength);
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= bindable_TextChanged;

    }
}

【问题讨论】:

    标签: xamarin xamarin.forms behavior


    【解决方案1】:
    entry.Behaviors.Add(new MaxLengthValidator { MaxLength = 2 });
    

    【讨论】:

    • 上述使用时找不到类型或命名空间MaxLengthValidator
    • 我假设你有 MaxLengthValidator 行为类,对吧?你应该只需要拉命名空间
    • 我确实错过了 MaxLengthValidator 类。添加类并引用它后,我的行为按预期工作。感谢您的帮助
    猜你喜欢
    • 2021-09-11
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2011-04-18
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    相关资源
    最近更新 更多