Data binding 未设置自定义控件的自定义属性-xamarin forms
我正在尝试使用EntryType属性创建一个自定义条目控件,然后在自定义呈现器中使用该属性来设置特定于平台的值。但是当从Xaml使用时,永远不会设置EntryType。这是我的密码:Data binding 未设置自定义控件的自定义属性-xamarin forms,data-binding,xamarin.forms,custom-controls,inotifypropertychanged,custom-renderer,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( propertyN
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)
{
}
}
}
公共类ExtendedEntryRenderer:EntryRenderer
{
公共ExtendedEntryRenderer(Android.Content.Context):基本(上下文)
{
}
受保护的覆盖无效OnElementChanged(ElementChangedEventArgs e)
{
基础。一个要素发生变化(e);
if(控件!=null)
{
var元素=(ExtendedEntry)元素;
Control.Hint=element.Placeholder;
开关(element.EntryType)
{
case EntryTextType.Numeric:
Control.SetRawInputType(Android.Text.InputTypes.ClassNumber);
打破
违约:
打破
}
}
}
受保护的覆盖无效OnElementPropertyChanged(对象发送方,PropertyChangedEventArgs e)
{
var p=e.PropertyName;
base.OnElementPropertyChanged(发送方,e);
}
}
然后在XAML中,我使用如下控件:
<controls:ExtendedEntry Placeholder="Password" IsPassword="True" Text="{Binding Secret}" EntryType="Any"/>
问题是,EntryType永远不会设置为EntryTextType.Any,并且始终使用默认值EntryTextType.Numeric。我错过了什么?谢谢。我注意到
EntryTypeProperty
声明中存在一些差异
- 声明类型应为所有者,即
ExtendedEntry
- 而且,要指示XAML使用enum
,必须将数据类型定义为TypeConverter
EntryTextType
public static readonly BindableProperty EntryTypeProperty = BindableProperty.Create(
propertyName: "EntryType",
returnType: typeof(EntryTextType),
declaringType: typeof(ExtendedEntry),
defaultValue: EntryTextType.Numeric
);
即使整数值为1,也会设置默认值。问题是,在xaml中分配的值永远不会被设置。因此,即使使用上述xaml,EntryType始终是数字的。我刚刚使用新属性进行了测试-它被设置为
Any
(因此我无法重现您的问题),但当我将returnType
更改回int
时,该值并不是通过xaml设置的。正如我在回答中提到的,您必须指示XAML处理器对枚举使用TypeConverter
——最简单的方法是将returnType
设置为right type。ohhh…给我一分钟时间进行验证。我不敢相信我一次都没试着把它调对。
<controls:ExtendedEntry Placeholder="Password" IsPassword="True" Text="{Binding Secret}" EntryType="Any"/>
public static readonly BindableProperty EntryTypeProperty = BindableProperty.Create(
propertyName: "EntryType",
returnType: typeof(EntryTextType),
declaringType: typeof(ExtendedEntry),
defaultValue: EntryTextType.Numeric
);