- Hands-On Mobile Development with .NET Core
- Can Bilgin
- 298字
- 2021-06-24 13:55:41
Composite customizations
Behaviors and effects, when used together, can create eloquent solutions to common native element requirements without having to resort to custom controls and renderers. Let's see how we can do this:
- Picking up from where we left off with the HtmlText effect, let's create an attached behavior that will allow us to switch the HTML rendering on/off:
public static class HtmlText
{
public static readonly BindableProperty IsHtmlProperty =
BindableProperty.CreateAttached("IsHtml",
typeof(bool), typeof(HtmlText), false,
propertyChanged: OnHtmlPropertyChanged);
private static void OnHtmlPropertyChanged(
BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as View;
if (view == null)
{
return;
}
if (newValue is bool isHtml && isHtml)
{
view.Effects.Add(new HtmlTextEffect());
}
else
{
var htmlEffect = view.Effects.FirstOrDefault(e => e is
HtmlTextEffect);
if (htmlEffect != null)
{
view.Effects.Remove(htmlEffect);
}
}
}
}
The behavior will be the addition or removal of the HTML effect, depending on the IsHtml property declaration.
- Now, we will modify our HTML effect so that it uses the existing text assignment on the forms view to create NSAttributedText and ISpannable for iOS and Android platforms, respectively:
public class HtmlTextEffect: PlatformEffect
{
protected override void OnAttached()
{
SetHtmlText();
}
protected override void OnDetached()
{
// TODO: Remove formatted text
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
if (args.PropertyName == Label.TextProperty.PropertyName)
{
SetHtmlText();
}
}
// Removed for brevity
}
Note that we have also used the OnElementPropertyChanged method to listen for Text property value changes. This would be the main access point for binding data.
- Now, we will add the behavior to our XAML:
<Label Text="{Binding Description}" effects:HtmlText.IsHtml="{Binding IsHtml}" />
We can now control the displayed text attributes on both platforms using the IsHtml attached property.
If none of these customization options provide what really required for the desired UI, a complete custom control implementation can be considered an option.
推薦閱讀
- 眼科急癥工作實(shí)用手冊
- 失眠認(rèn)知行為治療規(guī)范化培訓(xùn)教程
- 同仁眼外傷手冊
- 癲癇的診斷與治療:臨床實(shí)踐與思考
- 甲狀腺疾病的核醫(yī)學(xué)診斷與治療
- 頜面部疼痛外治法
- 臨床心理學(xué)
- 臨床急癥介入治療學(xué)
- 趙洪鈞醫(yī)學(xué)真?zhèn)?/a>
- 人工智能聲學(xué)屬性拓?fù)洌号两鹕?gòu)音障礙的信號分析與表示
- 實(shí)用人體體表解剖全真圖解
- 藥學(xué)監(jiān)護(hù)典型案例分析
- 神經(jīng)系統(tǒng)疾病與精神障礙
- 骨科疾病的分類與分型標(biāo)準(zhǔn)(第2版)
- 口腔癌、口咽癌:全生命周期診療及康復(fù)