UITextView绑定ViewModel时抛出MvxWeakEventSubscription异常求助
解决MvvmCross绑定UITextView.Text时的ArgumentNullException问题
我之前也碰到过这个一模一样的问题,根源在于Xamarin iOS的链接器优化过程中,把MvvmCross绑定UITextView.Text所需的NSTextStorage相关事件给移除了——哪怕你加了LinkerPleaseInclude,也可能因为没覆盖到正确的类型而无效。下面给你几个可行的解决办法:
方法1:完善LinkerPleaseInclude类,保留NSTextStorage的事件
修改你的LinkerPleaseInclude类,显式引用NSTextStorage的关键事件,让链接器不会把它们移除:
public class LinkerPleaseInclude { // 保留你已有的其他Include方法... // 添加这个方法,显式引用NSTextStorage的事件 public void Include(NSTextStorage storage) { storage.Changed += (sender, e) => { }; storage.WillProcessEditing += (sender, e) => { }; storage.DidProcessEditing += (sender, e) => { }; } }
这样链接器就会保留这些事件的元数据,MvvmCross的弱订阅机制就能找到对应的EventInfo,不会再抛出ArgumentNullException。
方法2:自定义只读文本绑定(适合你的Editable=false场景)
因为你的UITextView设置了Editable = false,其实只需要单向绑定(ViewModel到View),不需要监听文本变化事件。可以自定义一个绑定目标来绕过默认的MvxUITextViewTextTargetBinding:
步骤1:创建自定义目标绑定
public class MvxUITextViewReadOnlyTextTargetBinding : MvxConvertingTargetBinding { protected UITextView TextView => Target as UITextView; public MvxUITextViewReadOnlyTextTargetBinding(UITextView target) : base(target) { } public override Type TargetType => typeof(string); public override MvxBindingMode DefaultMode => MvxBindingMode.OneWay; protected override void SetValueImpl(object target, object value) { var textView = target as UITextView; if (textView == null) return; textView.Text = value?.ToString(); } }
步骤2:在Setup类中注册自定义绑定
public class Setup : MvxIosSetup<Core.App> { // 其他Setup代码... protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry) { base.FillTargetFactories(registry); // 注册自定义绑定 registry.RegisterCustomBindingFactory<UITextView>("ReadOnlyText", textView => new MvxUITextViewReadOnlyTextTargetBinding(textView)); } }
步骤3:修改绑定代码
把原来的绑定换成我们自定义的ReadOnlyText:
this.CreateBinding(MyTextView) .For("ReadOnlyText") .To<MyViewModel>(vm => vm.QuestionText) .Apply();
这种方法更贴合你的只读场景,完全避免了订阅NSTextStorage事件的需求。
方法3:临时关闭链接器(仅用于测试)
如果只是临时验证问题,可以在iOS项目的属性中,把链接器行为设置为"不要链接"。但这个方法会大幅增加App体积,绝对不推荐用于发布版本。
内容的提问来源于stack exchange,提问作者KING
相关产品推荐
相关产品推荐

