Skip to content

Instantly share code, notes, and snippets.

@Axemasta
Last active December 9, 2020 15:50
Show Gist options
  • Select an option

  • Save Axemasta/b4cdae16d11e50c967526f03e8779d10 to your computer and use it in GitHub Desktop.

Select an option

Save Axemasta/b4cdae16d11e50c967526f03e8779d10 to your computer and use it in GitHub Desktop.
Xamarin Forms Button With FormattedText
public class FormattedButton : Button
{
#region Properties
#region - Bindable Property Declaration
/// <summary>
/// Formatted Text Property
/// </summary>
public static readonly BindableProperty FormattedTextProperty = BindableProperty.Create(nameof(FormattedText), typeof(FormattedString), typeof(FormattedButton), default(FormattedString));
#endregion - Bindable Property Declaration
#region - Bindable Properties
/// <summary>
/// Gets or sets the Formatted Text
/// </summary>
public FormattedString FormattedText
{
get { return (FormattedString)GetValue(FormattedTextProperty); }
set { SetValue(FormattedTextProperty, value); }
}
#endregion - Bindable Properties
#endregion Properties
}
public class FormattedButtonRenderer : ButtonRenderer
{
public FormattedButtonRenderer(Context context) : base(context)
{
}
FormattedButton _formsButton
{
get { return Element as FormattedButton; }
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (Control == null || _formsButton == null)
return;
if (_formsButton.FormattedText == null || _formsButton.FormattedText.Spans == null || _formsButton.FormattedText.Spans.Count < 1)
return;
FormattedString formattedText = _formsButton.FormattedText ?? Element.Text;
var formatted = formattedText.ToAttributed(Element.Font, Element.TextColor, Control);
//https://tekeye.uk/android/examples/ui/android-app-text-not-updating
Device.BeginInvokeOnMainThread(() =>
{
Control.SetText(formatted, TextView.BufferType.Normal);
});
}
}
public class FormattedButtonRenderer : ButtonRenderer
{
FormattedButton _formsButton
{
get { return Element as FormattedButton; }
}
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (Control == null || _formsButton == null)
return;
if (_formsButton.FormattedText == null || _formsButton.FormattedText.Spans == null || _formsButton.FormattedText.Spans.Count < 1)
return;
_formsButton.Text = null;
var attributed = _formsButton.FormattedText.ToAttributed(Font.Default, Color.Default);
Control.SetAttributedTitle(attributed, UIKit.UIControlState.Normal);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment