xamarin - doc的附加行为与doc的附加属性?
问题描述
我想对条目输入进行一些验证,我去了附加行为的文档页面
并做到了:
public enum TextType { Email, Phone, }
public static class Validator
{
public static readonly BindableProperty TextTypeProperty = BindableProperty.CreateAttached(
"TextType", typeof(TextType), typeof(Validator), TextType.Email, propertyChanged: ValidateText);
public static TextType GetTextType(BindableObject view)
{
return (TextType)view.GetValue(TextTypeProperty);
}
public static void SetTextType(BindableObject view, TextType textType)
{
view.SetValue(TextTypeProperty, textType);
}
private static void ValidateText(BindableObject bindable, object oldValue, object newValue)
{
var entry = bindable as Entry;
entry.TextChanged += Entry_TextChanged;
}
private static void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
var entry = sender as Entry;
bool isValid = false;
switch (GetTextType(sender as Entry))
{
case TextType.Email:
isValid = e.NewTextValue.Contains("@");
break;
case TextType.Phone:
isValid = Regex.IsMatch(e.NewTextValue, @"^\d+$");
break;
default:
break;
}
if (isValid)
entry.TextColor = Color.Default;
else
entry.TextColor = Color.Red;
}
}
在 XAML 中:
<Entry beh:Validator.TextType="Email" Placeholder="Validate Email"/>
但它不起作用,setter 和propertyChanged
回调永远不会被调用,
这个“附加行为”和附加属性有什么区别,两个页面非常相同
解决方案
没有调用propertyChanged方法的逻辑有什么关系?
从这个 MSDN Attached Behaviors中,您可以看到附加属性可以定义一个 propertyChanged 委托,该委托将在属性值更改时执行。
根据您的代码,您首先设置 TextType=TextType.Email ,然后还设置
<Entry beh:Validator.TextType="Email" Placeholder="Validate Email"/>
Validator.TextType="Email",附加属性没有变化,所以没有调用 PropertyChanged 方法。
你可以像这样修改你的代码,然后你会发现 propertychanged 会被调用。
<Entry beh:Validator.TextType="Phone" Placeholder="Validate Email"/>
推荐阅读
- android - 如何设置此微调器文本的字体(字体)?
- django - Django crispy-forms:带有 TextArea 字段的 2 列表单
- sql - 使用 SQL 检索已订购商品的总数量
- sql - 在 Oracle 中使用 PARTITION BY 对行进行分组
- migration - 我是否需要将操作迁移到不使用 Dialogflow 的 v2?
- node.js - 为什么在 Express Node JS 中同时请求相同的路由时集群不起作用?
- c++ - 编译器会简化按顺序执行多次的操作吗?
- typescript - TextInput 目标值的类型是什么
- java - 未执行测试 - JUnit 5 以编程方式 + mvn exec
- python - 如何使用 CNN 和 pytorch 改进猫狗分类