DzMob Nadjib
DzMob Nadjib

Reputation: 13

Xamarin Forms WinPhone - How to make Label Text Underline WinPhone?

How can I make Label text Underline in WinPhone using Xamarin Forms ?

Upvotes: 1

Views: 789

Answers (4)

Syed Asad Ali
Syed Asad Ali

Reputation: 1328

Create a label renderer in your WinPhone project:

using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
[assembly: ExportRenderer(typeof(ExtendedLabel), typeof(ExtendedLabelRenderer))]

namespace SampleProject.WinPhone
{
public class ExtendedLabelRenderer: LabelRenderer
{
    ExtendedLabel element;
    TextBlock control;
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);

        if((ExtendedLabel)Element == null || Control == null)
            return;

        element = (ExtendedLabel)Element;
        control = Control;
        UnderlineText();
    }
    void UnderlineText()
    {
        control.Text = string.Empty;
        Underline ul = new Underline();
        Run run = new Run();
        run.Text = element.Text;
        ul.Inlines.Add(run);
        control.Inlines.Add(ul);
    }
  }
 }

Upvotes: 0

Rohit Vipin Mathews
Rohit Vipin Mathews

Reputation: 11787

You have top create a new control in your PCL/shared project inheriting from Label.

public class Exlabel : Label
{
}

In your windows phone project create a Custom Renderer for it as follows and use the TextBlock.TextDecorations Property to set the underline. The label is rendered as TextBlock in windows.

Sample (untested):

[assembly: ExportRenderer(typeof(Exlabel), typeof(ExlabelRenderer))]
namespace CustomRenderer.WinPhone81
{
    public class ExlabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                Control.TextDecorations = TextDecorations.UnderLine;
            }
        }
    }
}

If you are using the windows phone check out this sample - How to format texts of TextBlock using xaml in Windows Phone.

For WinRT you can use this - TextBlock underline in WinRT.

In SilverLight WinPhone (the old and not so supported template), you can also use the Margin to achieve what you require, similar to How to make an underlined input text field in Windows Phone?.

Upvotes: 1

Tolga Kartal
Tolga Kartal

Reputation: 633

Try using following xaml;

<StackLayout Orientation="Vertical">
    <Label Text="SomeText"/>
    <BoxView HeightRequest="1" HorizontalOptions="FillAndExpand" BackgroundColor="Black"/>
</StackLayout>

this should do it for all 3 platforms. :)

Upvotes: 0

Ahmad ElMadi
Ahmad ElMadi

Reputation: 2617

I think you need to create a custom view for this as a Layout/Grid that has a Label and a BoxView with a small heightRequest below the label to act as a line.

Upvotes: 0

Related Questions