如何在Xamarin Forms中将行为转换为通用类型?

3

我有一个“行为”负责在文本太短时上色。我想不仅在Entry控件中使用该行为,还要在许多其他控件中使用,如搜索栏或编辑器。我该如何将此行为转换为通用类型?是否可能?希望你理解我的意思。

public class MinLengthValidatonBehavior : Behavior<Entry>
{
    public static readonly BindableProperty MinLengthProperty =
        BindableProperty.Create("MinLength", typeof(int), typeof(MinLengthValidatonBehavior), 0);

    public static readonly BindableProperty InvalidColorProperty =
        BindableProperty.Create("InvalidColor", typeof(string), typeof(EmailValidatonBehavior), "e4375b");

    public int MinLength
    {
        get => (int)GetValue(MinLengthProperty);
        set => SetValue(MinLengthProperty, value);
    }

    public string InvalidColor
    {
        get => GetValue(InvalidColorProperty).ToString();
        set => SetValue(InvalidColorProperty, value);
    }

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

    private void BindableTextChanged(object sender, TextChangedEventArgs e)
    {
        (sender as Entry).TextColor =
            e.NewTextValue.Length < MinLength ? Color.FromHex(InvalidColor) : Color.Default;
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= BindableTextChanged;
    }
}
1个回答

0

抱歉很久没有写信了。我之前尝试过,但出现了错误:在泛型类型或方法“Behavior<T>”中,类型“T”不能用作类型参数“T”。从“T”到“Xamarin.Forms.BindableObject”不存在装箱转换或类型参数转换。 - vamteusz
这里有一个类似的帖子解决了你的问题 here. 看一下,如果不够详细,尝试提供更多数据。 - Uraitz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接