doc的附加行为与doc的附加属性?

时间:2019-03-24 21:45:38

标签: xamarin xamarin.forms

我想对输入项进行验证,我进入了attached behaviors的docs页面

并这样做:

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回调,

此“附加行为”与attached property有什么区别,两个页面完全相同

2 个答案:

答案 0 :(得分:1)

  

未调用propertyChanged方法与逻辑有什么关系?

从此MSDN Attached Behaviors,您可以看到附加属性可以定义一个propertyChanged委托,该委托将在属性值更改时执行。

根据您的代码,首先设置TextType = TextType.Email,然后再设置

<Entry beh:Validator.TextType="Email" Placeholder="Validate Email"/>

Validator.TextType =“ Email”,附加属性不会更改,因此不会调用PropertyChanged方法。

您可以像这样修改代码,然后发现更改后的属性将被调用。

<Entry beh:Validator.TextType="Phone" Placeholder="Validate Email"/>

答案 1 :(得分:0)

与示例相比,您忽略了ValidateText中OnAttachBehaviorChanged的大多数逻辑,这是非常必要的:

    static void OnAttachBehaviorChanged (BindableObject view, object oldValue, object newValue)
{
    var entry = view as Entry;
    if (entry == null) {
        return;
    }

    bool attachBehavior = (bool)newValue;
    if (attachBehavior) {
        entry.TextChanged += OnEntryTextChanged;
    } else {
        entry.TextChanged -= OnEntryTextChanged;
    }
}

考虑到差异,附加属性是应用于特定控件的内容,您可以从技术上将行为应用于任何控件,尽管它可能仅适用于其中某些控件,但可能适用于多种控件类型。