.NET MAUI 7:自定义Bindable Property绑定Attached Property无响应求助
解决方案
1. 修正XAML中的自定义视图类型错误
你的XAML中使用了<views:CustomView>,但自定义属性ShouldAnimateOut是定义在UserCredentialsView类中的,两者不匹配会直接导致绑定失效。将XAML中的视图类型改为正确的类名:
<views:UserCredentialsView Margin="0,0,0,20" attached:AttachedProperty.Animate="False" ShouldAnimateOut="{Binding (attached:AttachedProperty.Animate), Source={RelativeSource Mode=Self}}" StrokeThickness="0" x:Name="myCustomView" Padding="10,10" VerticalOptions="End" Background="#345173" HeightRequest="200"> <views:UserCredentialsView.GestureRecognizers> <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/> </views:UserCredentialsView.GestureRecognizers> </views:UserCredentialsView>
2. 调整自定义属性的绑定模式避免循环更新
ShouldAnimateOut设置为TwoWay绑定模式,同时在其变更事件中强制将AttachedProperty.Animate设为false,会触发双向绑定的循环冲突:附加属性变更→自定义属性变更→附加属性被强制重置→自定义属性再次变更,干扰绑定系统的正常同步逻辑。
根据你的需求,ShouldAnimateOut仅需同步AttachedProperty.Animate的变更,将绑定模式改为OneWay即可:
public class UserCredentialsView : Border { public static readonly BindableProperty ShouldAnimateOutProperty = BindableProperty.Create(nameof(ShouldAnimateOut), typeof(bool), typeof(UserCredentialsView), false, BindingMode.OneWay, propertyChanged: ShouldAnimateOutPropertyChanged); private static void ShouldAnimateOutPropertyChanged(BindableObject bindable, object oldValue, object newValue) { AttachedProperty.SetAnimate(bindable, false); } public bool ShouldAnimateOut { get => (bool)GetValue(ShouldAnimateOutProperty); set => SetValue(ShouldAnimateOutProperty, value); } }
3. 优化点击事件的类型转换
将点击事件中的sender转换为准确的UserCredentialsView类型,避免不必要的类型转换问题:
private void TapGestureRecognizer_Tapped(object sender, TappedEventArgs e) { var mControl = sender as UserCredentialsView; if (mControl == null) return; AttachedProperty.SetAnimate(mControl, !AttachedProperty.GetAnimate(mControl)); }
核心问题总结
- 视图类型不匹配:XAML中使用的视图类无
ShouldAnimateOut属性,绑定系统无法识别目标属性,导致变更事件无法触发。 - 双向绑定循环:
TwoWay模式下自定义属性的反向更新与手动强制重置附加属性的逻辑冲突,干扰了绑定值的同步流程。
内容的提问来源于stack exchange,提问作者yigit sertac
相关产品推荐
相关产品推荐

