6
votes

I am developing a xamarin forms project. I need to a Label with in a listview which by default display max of 2 lines and then shows elipses(...) also I want to add a readmore button which enable the user to view the truncated text. Again the text need to be truncated when button is clicked. It is like "See more" & "See less" functionality. I have made it display 3 by using max lines property. Please anyone suggest me how to achieve this. I have added the screenshot for further reference.

This is my XAML For the label.

<Label Text="{Binding Note, Mode=TwoWay}" Padding="0,0,0,0" MaxLines="3"
       LineBreakMode="TailTruncation" Style="{StaticResource TabContentLabelStyle}" 
       IsVisible="{Binding IsEdit,Converter={StaticResource BoolConverter}}" />

See more Image

This is how it should look when Collapsed:

2
@Anand This is not the answer , he is expecting.Sagar Panwala

2 Answers

1
votes

Made a quick sample based on what @anand said

enter image description here

Create custom control called CustomLabel

CustomLabel.xaml

<ContentView
    x:Class="BlankApp3.Controls.CustomLabel"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:prism="http://prismlibrary.com"
    mc:Ignorable="d">

    <ContentView.Content>
        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <Label x:Name="customLabel" />
            <Label
                x:Name="lblReadMore"
                FontSize="18"
                TextColor="#1a0fa9">
                <Label.GestureRecognizers>
                    <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
                </Label.GestureRecognizers>
            </Label>
        </StackLayout>
    </ContentView.Content>
</ContentView>

Code behind

using System;
using System.Diagnostics;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace BlankApp3.Controls
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomLabel : ContentView
    {
        public CustomLabel()
        {
            InitializeComponent();
        }

        #region Bindable Property

        public static readonly BindableProperty TextProperty = BindableProperty.Create(
            propertyName: nameof(TextProperty),
            returnType: typeof(string),
            declaringType: typeof(CustomLabel),
            defaultBindingMode: BindingMode.TwoWay,
            propertyChanged: TextPropertyChanged
            );

        public string Text
        {
            get { return (string)base.GetValue(TextProperty); }
            set { base.SetValue(TextProperty, value); }
        }

        private static void TextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (CustomLabel)bindable;
            if (newValue != null)
            {
                control.customLabel.Text = (string)newValue;
                var ss = control.customLabel.Text.Split().Length;
                if (control.customLabel.Text.Split().Length >= 30)
                {
                    control.ShortTextVisible = true;
                    control.ReadMoreLabel = true;
                }
            }
        }

        #endregion Bindable Property

        public bool ReadMoreLabel { get; set; }
        private bool _shortTextVisible;

        public bool ShortTextVisible
        {
            get => _shortTextVisible;
            set { _shortTextVisible = value; ShortTextPropertyChanged(); }
        }

        private void ShortTextPropertyChanged()
        {
            if (Text != null && Text.Split().Length >= 30)
            {
                if (ShortTextVisible)
                {
                    if (customLabel != null && !string.IsNullOrWhiteSpace(customLabel.Text) && customLabel.Text.Split().Length < 100)
                    {
                        Debug.WriteLine("");
                    }

                    customLabel.Text = string.Join(" ", Text.Split().Take(30));
                    lblReadMore.Text = "See more";
                    lblReadMore.IsVisible = true;
                }
                else
                {
                    customLabel.Text = Text;
                    lblReadMore.Text = "See less";
                }
            }
        }

        private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
        {
            ShortTextVisible = !ShortTextVisible;
        }
    }
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="BlankApp3.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:BlankApp3.Controls"
    Title="{Binding Title}"
    BackgroundColor="#ffffff">

    <CollectionView ItemsSource="{Binding Monkeys}">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>

                    <StackLayout Padding="10" Orientation="Horizontal">

                        <Image
                            HeightRequest="80"
                            Source="https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX13204546.jpg"
                            VerticalOptions="Start" />

                        <StackLayout HorizontalOptions="FillAndExpand">
                            <Frame
                                Margin="10,0,10,0"
                                BackgroundColor="#f9f9f9"
                                CornerRadius="10"
                                HasShadow="False">
                                <StackLayout>
                                    <Label FontAttributes="Bold" Text="Dr. Gracy David" />
                                    <local:CustomLabel Text="{Binding .}" />
                                </StackLayout>
                            </Frame>

                            <StackLayout Margin="10,0,10,0" Orientation="Horizontal">
                                <Label Text="12 April,2020" />
                                <Label Text="3.20pm" />
                            </StackLayout>
                        </StackLayout>
                    </StackLayout>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</ContentPage>   

MainPageViewModal.cs

using Prism.Navigation;
using System.Collections.ObjectModel;

namespace BlankApp3.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        public ObservableCollection<string> Monkeys { get; set; }

        public MainPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            Title = "Main Page";

            Monkeys = new ObservableCollection<string>();
        }

        public async override void OnNavigatedTo(INavigationParameters parameters)
        {
            Monkeys = new ObservableCollection<string>()
            {
                 "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
                 "Simple",
                 "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
            };
        }
    }
}
0
votes

You could use FormattedText, as in this example:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/label#formatted-text

and use the command on the last Span(make it look like a hyper link) to expand / collapse the text.

The first Span's Text property can bind to viewmodel's text property that will have part of the full text, and upon command execute will have the full text.