官术网_书友最值得收藏!

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:

  1. 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.

  1. 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.

  1. 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.

主站蜘蛛池模板: 嘉义县| 乌拉特中旗| 罗定市| 枣强县| 湘乡市| 鄂托克前旗| 灵川县| 古丈县| 育儿| 江阴市| 宁夏| 宁津县| 博乐市| 富锦市| 南陵县| 衡阳县| 垦利县| 广安市| 班戈县| 石河子市| 尼玛县| 丁青县| 广宁县| 鹤峰县| 昌都县| 泗水县| 枣庄市| 北宁市| 灵寿县| 新疆| 沁水县| 读书| 湄潭县| 涪陵区| 洮南市| 鄂伦春自治旗| 土默特左旗| 广汉市| 西丰县| 大足县| 漾濞|