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