为什么默认值为null时不会触发propertyChanged?

时间:2019-03-30 12:55:50

标签: xamarin xamarin.forms attached-properties attachedbehaviors

我有以下这种行为:

public enum TextType { Email, Phone, }
    public static class Validator
    {
           public static readonly BindableProperty TextTypeProperty = BindableProperty.CreateAttached(
        "TextType", typeof(TextType), typeof(Validator), null, 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 TextTypeChanged(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"/>

在此页面上运行应用程序时,除非我将TextTypeChanged更改为defaultValue枚举的成员,否则不会调用TextType

0 个答案:

没有答案