首页 > 解决方案 > 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回调永远不会被调用,

这个“附加行为”和附加属性有什么区别,两个页面非常相同

标签: xamarinxamarin.forms

解决方案


没有调用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"/>

推荐阅读