我有一個自定義的渲染器在UITextView中顯示HTML格式的文本。如果我將文本硬編碼到包含控件的頁面的構造函數中(因此它被設置在自定義控件的OnElementChanged事件中),它顯示正常。如果我等待一個api調用來獲取文本,然後設置它(所以它被設置在自定義控件的OnElementPropertyChanged事件中),它不會重繪。如果我更改設備的方向,則會顯示文本。我需要添加什麼才能讓它在設置時顯示文本?Xamarin Forms iOS CustomRenderer不重繪
[assembly: ExportRenderer(typeof(HtmlLabel), typeof(HtmlLabelRenderer))]
namespace MyApp.iOS.Renderers
{
class HtmlLabelRenderer : ViewRenderer<HtmlLabel, UITextView>
{
private UITextView _htmlTextView = new UITextView();
protected override void OnElementChanged(ElementChangedEventArgs<HtmlLabel> e)
{
base.OnElementChanged(e);
if (Element?.Text == null) return;
SetHtmlText(Element.Text);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (string.Equals(e.PropertyName, "Text", StringComparison.CurrentCultureIgnoreCase))
{
SetHtmlText(((HtmlLabel)sender).Text);
_htmlTextView.SetNeedsDisplay();
}
base.OnElementPropertyChanged(sender, e);
}
private void SetHtmlText(string text)
{
var attr = new NSAttributedStringDocumentAttributes {DocumentType = NSDocumentType.HTML};
var nsError = new NSError();
_htmlTextView.Editable = false;
_htmlTextView.AttributedText = new NSAttributedString(text, attr, ref nsError);
_htmlTextView.DataDetectorTypes = UIDataDetectorType.All;
SetNativeControl(_htmlTextView);
}
}
}
更新:現在
protected override void OnElementChanged(ElementChangedEventArgs<HtmlLabel> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null) return;
SetHtmlText(e.NewElement.Text ?? string.Empty);
SetNativeControl(_htmlTextView);
}
,如果我有一個以上的HtmlLabel頁面上的所有除第一個顯示:我得到了進一步通過改變OnElementChanged來。
我試過了,沒有效果 – Christine
好 - 只是爲了確認,是' 'HtmlLabel'上的Text屬性是一個可綁定的屬性?如果可以,可以發佈'HtmlLabel'的代碼。 – Ada
沒有,是HtmlLabel無碼 - 公共類HtmlLabel:標籤 { } 我把它添加到頁面 StackLayout> 然後在檢索到代碼後設置代碼中的文本 HtmlDescription.Text = announcement.Details; –
Christine