流行模式和自定义 iOS 渲染器上的空引用



我有一个模态视图,其中我有多个Entry字段,我通过iOS自定义渲染器自定义了这些字段,以便在Focused时更改BorderColor

当我在按下按钮时弹出我的模态视图时:

await Navigation.PopModalAsync(true);

我在我的 iOS 自定义渲染器中得到了一个 null引用,因为我想该元素突然变为 null,而且我不知何故没有告诉它,视图消失了。

public class BorderColorChange : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Layer.BorderWidth = 1;
Control.Layer.CornerRadius = 4;
e.NewElement.Focused += (sender, evt) =>
{
Control.Layer.BorderColor = UIColor.FromRGB(3, 169, 244).CGColor;
};
e.NewElement.Unfocused += (sender, evt) =>
{
Control.Layer.BorderColor = UIColor.LightGray.CGColor;
};
};
}
}

我注意到,当我从Navigation.PopModalAsync(true);中删除await关键字时,它不会产生错误。

关于如何解决此错误的任何帮助?

使用 e.NewElement==null 调用 OnElementChanged 是完全正常的。 这仅意味着该元素正在被删除(例如,当您等待 PopModelAsync 时(,因此它应该处理要关联的新元素为 null 的更改。

使用自定义呈现器时,当自定义呈现器与本机控件关联时发生更改时,需要订阅和取消订阅事件。所以例如:

public class BorderColorChange : EntryRenderer
{
private void MyFocusedEventHandler(...) ...
private void MyUnfocusedEventHandler(...) ...
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Layer.BorderWidth = 1;
Control.Layer.CornerRadius = 4;
if (e.OldElement != null)  // unsubscribe from events on old element
{
e.OldElement.Focused -= MyFocusedEventHandler;
e.OldElement.Unfocused -= MyUnfocusedEventHandler;
}
if (e.NewElement != null)  // subscribe to events on new element
{
e.NewElement.Focused += MyFocusedEventHandler;
e.NewElement.Unfocused += MyUnfocusedEventHandler;
}
}
}
}

当条目获得/失去焦点时要执行的操作的逻辑进入 MyFocusedEventHandler/MyUnfocusedEventHandler 而不是内联以允许订阅和取消订阅。

最新更新