未设置自定义控件的自定义属性-Xamarin表单

时间:2018-08-09 14:42:34

标签: data-binding xamarin.forms custom-controls inotifypropertychanged custom-renderer

我试图用EntryType属性创建一个自定义条目控件,然后在自定义渲染器内部使用它来设置平台特定的值。但是从Xaml使用时,永远不会设置EntryType。这是我的代码:

public class ExtendedEntry : Xamarin.Forms.Entry
{

    public static readonly BindableProperty EntryTypeProperty = BindableProperty.Create(
        propertyName: "EntryType",
        returnType: typeof(int),
        declaringType: typeof(EntryTextType),
        defaultValue: 1
        );

    public EntryTextType EntryType
    {
        get
        {
            return (EntryTextType)GetValue(EntryTypeProperty);
        }
        set
        {
            SetValue(EntryTypeProperty, value);

        }
    }

    protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        base.OnPropertyChanged(propertyName);

        if (propertyName == EntryTypeProperty.PropertyName)
        {

        }
    }
}

public enum EntryTextType
{
    Any,
    Numeric,
    Url,
    Email
}

public class ExtendedEntryRenderer : EntryRenderer
{
    public ExtendedEntryRenderer(Android.Content.Context context) : base(context)
    {

    }

    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            var element = (ExtendedEntry)Element;
            Control.Hint = element.Placeholder;
            switch(element.EntryType)
            {
                case EntryTextType.Numeric:
                    Control.SetRawInputType(Android.Text.InputTypes.ClassNumber);
                    break;
                default:
                    break;
            }
        }
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        var p = e.PropertyName;
        base.OnElementPropertyChanged(sender, e);
    }

}

然后在XAML中,按如下方式使用控件:

<controls:ExtendedEntry Placeholder="Password" IsPassword="True" Text="{Binding Secret}" EntryType="Any"/>

问题在于, EntryType永远不会设置为EntryTextType.Any ,并且始终使用EntryTextType.Numeric的默认值。我在这里想念什么?谢谢。

1 个答案:

答案 0 :(得分:0)

我注意到EntryTypeProperty声明中有一些差异。

  • 声明类型应为ExtendedEntry的所有者
  • 并且,要指示XAML使用枚举TypeConverter,您必须将数据类型定义为EntryTextType

因此您的新代码将如下所示:

public static readonly BindableProperty EntryTypeProperty = BindableProperty.Create(
    propertyName: "EntryType",
    returnType: typeof(EntryTextType),
    declaringType: typeof(ExtendedEntry),
    defaultValue: EntryTextType.Numeric
    );