我找到了一个如何在Xamarin中实现自定义webview的指南。
public class CustomWebView : WebView
{
Action<string> action;
public static readonly BindableProperty PostUrlProperty =
BindableProperty.Create(nameof(PostUrl), typeof(string), typeof(CustomWebView), string.Empty, BindingMode.OneWay);
public string PostUrl
{
get { return (string)GetValue(PostUrlProperty); }
set { SetValue(PostUrlProperty, value); }
}
public byte[] PostData { get; set; } = new byte[0];
public void RegisterAction(Action<string> callback)
{
action = callback;
}
public void Cleanup()
{
action = null;
}
public void InvokeAction(string data)
{
if (action == null || data == null)
{
return;
}
action.Invoke(data);
}
}
安卓系统:
[assembly: ExportRenderer(typeof(CustomWebView), typeof(HybridWebViewRenderer))]
名称空间{公共类混合网络视图呈现器:WebViewRenderer {公共混合WebViewRenderer(上下文上下文):基础(上下文){ }
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "PostUrl") //e.PropertyName is never PostUrl
{
if (Control == null)
return;
Android.Webkit.WebView web = Control;
CustomWebView view = Element as CustomWebView;
web.PostUrl(view.PostUrl, view.PostData);
}
}
}
}
主页
System.Text.Encoding encoding = Encoding.UTF8;
byte[] bytes = encoding.GetBytes(postData);
string url = "myUrl";
hybridWebView.PostData = bytes;
hybridWebView.PostUrl = url;
MainPge.xaml
<?xml version="1.0" encoding="utf-8" ?>
<renderer:CustomWebView x:Name="hybridWebView"/>
我无法获取e。属性名称为PostUrl
我错过了什么
1条答案
按热度按时间ecfdbz9o1#
您是否将
hybridWebView.PostUrl = url
放入MainPage的构造方法中?我已经做了一个示例来测试,发现MainPage的构造方法将在HybridWebViewRenderer的构造方法之前执行。因此,在
hybridWebView.PostUrl = url
完成之前不会调用OnElementPropertyChanged
方法。我创建了一个按钮,并将
hybridWebView.PostUrl = url
放入按钮的clicked事件中。然后当我单击按钮时,我会得到e.PropertyName == "PostUrl"
。所以你可以试试。