Xamarin Forms自定义Behavior绑定BindableProperty失败排查
解决Xamarin.Forms自定义Behavior绑定XFC0009错误的方案
问题场景
为Entry控件实现了自定义Behavior MobileNumberValidation,包含MobileCountryCode和IsInValid两个BindableProperty。硬编码属性值时功能正常,但绑定页面ViewModel属性时触发XFC0009错误:找不到对应属性、BindableProperty或事件,或类型不匹配。其中MobileCountryCode设置BindingContext后绑定恢复正常,但IsInValid绑定ViewModel的布尔属性IsMobileNoValid时仍报错,仅硬编码False可正常运行。
错误原因
问题核心在于IsInValid对应的BindableProperty定义错误:
IsInValidProperty被声明为private static,而Xamarin.Forms要求所有需要在XAML中绑定的BindableProperty必须是public static,否则XAML解析器无法识别该属性,导致绑定失败。MobileCountryCodeProperty是public修饰的,因此设置BindingContext后能正常绑定,对比之下更能确认是访问修饰符的问题。
解决方案
将IsInValidProperty的访问修饰符从private改为public,确保XAML解析器可以识别这个BindableProperty。
修改后的代码示例
public class MobileNumberValidation:Behavior<Entry> { // 修正:将private改为public public static readonly BindableProperty IsInValidProperty = BindableProperty.Create(nameof(IsInValid),typeof(bool),typeof(MobileNumberValidation),defaultValue:false); public bool IsInValid { get=>(bool)GetValue(IsInValidProperty); set => SetValue(IsInValidProperty, value); } public static readonly BindableProperty MobileCountryCodeProperty = BindableProperty.Create(nameof(MobileCountryCode) ,typeof(string),typeof(MobileNumberValidation) ,defaultValue:String.Empty); public string MobileCountryCode { get=> (string)GetValue(MobileCountryCodeProperty); set => SetValue(MobileCountryCodeProperty, value); } protected override void OnAttachedTo(Entry bindable) { base.OnAttachedTo(bindable); bindable.Unfocused += Bindable_Unfocused; } protected override void OnDetachingFrom(Entry bindable) { base.OnDetachingFrom(bindable); bindable.Unfocused -= Bindable_Unfocused; } private void Bindable_Unfocused(object sender, FocusEventArgs e) { // 验证逻辑 } }
XAML代码无需修改,保持原有绑定即可:
<Entry x:Name="ent_MobileNo" Grid.Column="1" Keyboard="Email" Placeholder="{behaviors:Translate MobilePlaceHolder}" Text="{Binding MobileNo}"> <Entry.Behaviors> <customBehaviour:MobileNumberValidation x:Name="MobileNoFormat" BindingContext="{Binding Path=BindingContext, Source={Reference thisPage}}" IsInValid="{Binding IsMobileNoValid}" MobileCountryCode="{Binding MobileCountryCodeSelected.MobileCode}" /> </Entry.Behaviors> </Entry>
内容的提问来源于stack exchange,提问作者Ashish
相关产品推荐
相关产品推荐

