Xamarin Forms: How to Change the textcolor of Collectionview SelectedItem?

对着背影说爱祢 提交于 2021-02-11 13:59:50

问题


I have a CarouselPage having 5 children and every child has a horizontal collection view. When selecting an item in Collectionview or swiping the pages, I need to give a different text color and need to add an underline for the selected item. I have tried like below:

CarouselHomePage.cs

public partial class CarouselHomePage : CarouselPage
{
    public List<Activity> activityList { get; set; }
    public CarouselHomePage()
    {
        InitializeComponent(); 
        activityList = new List<Activity>();
        AddActivities();

        MessagingCenter.Subscribe<App, string>((App)Xamarin.Forms.Application.Current, "child", (s, child) =>
        {
            CurrentPage = Children[Int32.Parse(child)];
        });
    }

    private void AddActivities()
    {
        activityList.Add(new Activity() { Title = "PageNumber1" });
        activityList.Add(new Activity() { Title = "PageNumber2" });
        activityList.Add(new Activity() { Title = "PageNumber3" });
        activityList.Add(new Activity() { Title = "PageNumber4" });
        activityList.Add(new Activity() { Title = "PageNumber5" });
        AddChild(activityList);
    }

    public void AddChild(List<Activity> activityList)
    {
        this.Children.Add(new PageNumber1(activityList));
        this.Children.Add(new PageNumber2(activityList));
        this.Children.Add(new PageNumber3(activityList));
        this.Children.Add(new PageNumber4(activityList));
        this.Children.Add(new PageNumber5(activityList));
    }
}

Activity.cs

public class Activity
{
    public string Title { get; set; }

    public bool visibility { get; set; }
    public bool Visibility
    {
        set
        {
            if (value != null)
            {
                visibility = value;
                NotifyPropertyChanged();
            }
        }
        get
        {
            return visibility;
        }
    }

    private Color textColor;
    public Color TextColor
    {
        set
        {
            if (value != null)
            {
                textColor = value;
                NotifyPropertyChanged();
            }
        }
        get
        {
            return textColor;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

PageNumber1.xaml

<ContentPage.Content>
    <StackLayout Orientation="Vertical">
        <CollectionView 
            SelectionMode="Single"
            x:Name="ActivityList"
            Margin="5,10,5,10"
            SelectionChanged="TagItemTapped"
            ItemsLayout="HorizontalList">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout 
                        Orientation="Vertical"
                        Margin="15">

                        <Label
                            TextColor="{Binding TextColor}"
                            HorizontalTextAlignment="Center"
                            VerticalTextAlignment="Center"
                            Text="{Binding Title}">
                            <Label.FontSize>
                                <OnIdiom x:TypeArguments="x:Double">
                                    <OnIdiom.Phone>18</OnIdiom.Phone>
                                    <OnIdiom.Tablet>27</OnIdiom.Tablet>
                                    <OnIdiom.Desktop>18</OnIdiom.Desktop>
                                </OnIdiom>
                            </Label.FontSize>
                        </Label>

                        <BoxView 
                            HeightRequest="2"
                            IsVisible="{Binding Visibility}"
                            BackgroundColor="{Binding TextColor}" 
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Start"/>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
            <CollectionView.HeightRequest>
                <OnIdiom x:TypeArguments="x:Double">
                    <OnIdiom.Phone>30</OnIdiom.Phone>
                    <OnIdiom.Tablet>60</OnIdiom.Tablet>
                    <OnIdiom.Desktop>30</OnIdiom.Desktop>
                </OnIdiom>
            </CollectionView.HeightRequest>
        </CollectionView>

        <Label Text="Welcome to PageNumber1"
            VerticalOptions="CenterAndExpand" 
            HorizontalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage.Content>

PageNumber1.xaml.cs

public partial class PageNumber1 : ContentPage
{
    public PageNumber1(List<Activity> activityList)
    {
        InitializeComponent();
        if (activityList == null)
        {
            ActivityList.IsVisible = false;
        }
        else
        {
            for (int i = 0; i < activityList.Count; i++)
            {
                if (activityList[i].Title == "PageNumber1")
                {
                    activityList[i].TextColor = Color.FromHex("#26b4d8");
                    activityList[i].Visibility = true;
                }
                else
                {
                    activityList[i].TextColor = Color.Gray;
                    activityList[i].Visibility = false;
                }
            }
            ActivityList.ItemsSource = activityList;
        }
    }
    public void TagItemTapped(object sender, SelectionChangedEventArgs e)
    {
        var selectedItem = (e.CurrentSelection.FirstOrDefault() as Activity);
        if (selectedItem != null)
        {
            string childnumber = "";
            if (selectedItem.Title == "PageNumber1")
            {
                childnumber = "0";
            }
            else if (selectedItem.Title == "PageNumber2")
            {
                childnumber = "1";
            }
            else if (selectedItem.Title == "PageNumber3")
            {
                childnumber = "2";
            }
            else if (selectedItem.Title == "PageNumber4")
            {
                childnumber = "3";
            }
            else if (selectedItem.Title == "PageNumber5")
            {
                childnumber = "4";
            }
            MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "child", childnumber);
        }
    }
}

I have added the same code on all the other child pages with the corresponding title in the if statement. But the selected page title color is not working and underline is not showing.

Screenshot:

Also if I select the last item in the collectionview, I need to scroll the collection on the last child to the last item. For this I have used ScrollTo feature of Collectioview. But that is also not working.

protected override void OnAppearing()
{
    ActivityList.ScrollTo(4);
}

The above code will work if I manually swipe the pages. When directly tap the collectionview item, the scrolling is not working.

I have uploaded a sample project here.


回答1:


About underline not showing , the reason is HeightRequest of CollectionView setted too small with 30 .

Modify that to above 35 , it will show correcttly . Such as :

<CollectionView.HeightRequest>
    <OnIdiom x:TypeArguments="x:Double">
        <OnIdiom.Phone>40</OnIdiom.Phone>
        <OnIdiom.Tablet>60</OnIdiom.Tablet>
        <OnIdiom.Desktop>30</OnIdiom.Desktop>
    </OnIdiom>
</CollectionView.HeightRequest>

The effect :

About selected problem , this is the sample project here .



来源:https://stackoverflow.com/questions/61379921/xamarin-forms-how-to-change-the-textcolor-of-collectionview-selecteditem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!