c# - 如何在 Xamarin Forms 中将行为转换为泛型类型?

标签 c# xamarin xamarin.forms

我有一个行为,如果他太短,它负责为文本着色。我不仅想将行为用于 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;
    }
}

最佳答案

你可以使用 MinLengthValidatonBehavior<T> : Behavior<T>并正确指定类型 typeof(MinLengthValidatonBehavior<T>确保您绑定(bind)的属性在您使用的所有 T 元素中可用。

您可以在官方网页上了解更多。

https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/behaviors/introduction/

关于c# - 如何在 Xamarin Forms 中将行为转换为泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46293501/

相关文章:

c# - ASP.NET - Window.Open(URL) - 文件被缓存,如何停止?

c# - 正则表达式 - 在字符串中查找 4 位数字

c# - 如何从任务栏(WPF)隐藏打开的子窗口?

ios - 为什么自动布局预览和实际设备不匹配

ios - 如何在xamarin中隐藏ios导航栏后退按钮

xamarin - 如果未在使用模板的 XAML 中指定,我怎样才能使模板内的 HeightRequest 被忽略?

c# - 如何对网页上的文本进行加密?

xaml - Xamarin.Forms:无法解析程序集或 Windows 元数据文件 'Type universe cannot resolve assembly: MyApp.UI.Base...'

xamarin.forms 如何使用 Entry 选择焦点上的所有文本?

ios - Xamarin Forms Shell 覆盖 iOS (iPad) 上的顶级信息行