Xamarin.macOS CustomWebView 的导航事件未触发
Xamarin.macOS Navigated event not fire for CustomWebView
我已经为我的 WebView 创建了自定义渲染器,因为我需要设置 属性 CustomUserAgent。但是对于我的 CustomWebView 事件 Navigated 没有被触发。据我了解,我需要设置 NavigationDelegate 但找不到任何工作示例。这是我的代码:
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace DesktopClient.MacOS.CustomRenderers
{
public class CustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
{
private WKWebView wkWebView;
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if (this.Control == null)
{
WKWebViewConfiguration config = new();
this.wkWebView = new WKWebView(this.Frame, config)
{
NavigationDelegate = new WKNavigationDelegate()
};
this.SetNativeControl(this.wkWebView);
WKWebViewContainer.WKWebView = this.wkWebView;
}
if (e.NewElement != null)
{
UrlWebViewSource source = (UrlWebViewSource)e.NewElement.Source;
if (source != null)
{
this.Control.LoadRequest(new NSUrlRequest(new NSUrl(source.Url)));
}
this.Control.CustomUserAgent = e.NewElement.UserAgent;
this.wkWebView.NavigationDelegate = new WKNavigationDelegate();
}
}
}
}
创建一个新的class继承自WKNavigationDelegate
并分配给Webview.NavigationDelegate
,然后你可以在新的class中重写DidFinishNavigation
的方法.
示例代码
NavigationDelegate = new MyDelegate();
public class MyDelegate : WKNavigationDelegate {
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
}
}
但是,我发现 DidFinishNavigation
方法在初始加载时不会触发,它只能在我们导航到其他网页时触发。
我已经为我的 WebView 创建了自定义渲染器,因为我需要设置 属性 CustomUserAgent。但是对于我的 CustomWebView 事件 Navigated 没有被触发。据我了解,我需要设置 NavigationDelegate 但找不到任何工作示例。这是我的代码:
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace DesktopClient.MacOS.CustomRenderers
{
public class CustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
{
private WKWebView wkWebView;
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if (this.Control == null)
{
WKWebViewConfiguration config = new();
this.wkWebView = new WKWebView(this.Frame, config)
{
NavigationDelegate = new WKNavigationDelegate()
};
this.SetNativeControl(this.wkWebView);
WKWebViewContainer.WKWebView = this.wkWebView;
}
if (e.NewElement != null)
{
UrlWebViewSource source = (UrlWebViewSource)e.NewElement.Source;
if (source != null)
{
this.Control.LoadRequest(new NSUrlRequest(new NSUrl(source.Url)));
}
this.Control.CustomUserAgent = e.NewElement.UserAgent;
this.wkWebView.NavigationDelegate = new WKNavigationDelegate();
}
}
}
}
创建一个新的class继承自WKNavigationDelegate
并分配给Webview.NavigationDelegate
,然后你可以在新的class中重写DidFinishNavigation
的方法.
示例代码
NavigationDelegate = new MyDelegate();
public class MyDelegate : WKNavigationDelegate {
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
}
}
但是,我发现 DidFinishNavigation
方法在初始加载时不会触发,它只能在我们导航到其他网页时触发。