简体   繁体   English

更改列表视图中所选项目的属性

[英]Change attributes for selected items in listview

Hi I'm trying to develop an easy quiz app.您好,我正在尝试开发一个简单的测验应用程序。 But I'm having problem with changing attributes on the selected items.但是我在更改所选项目的属性时遇到问题。 I tried with Frame.Triggers but it didn't work so I'm looking for alternatives now.我尝试使用 Frame.Triggers 但它没有用,所以我现在正在寻找替代品。

So the main idea is to change the backgroundcolor of the item and the text color when the item is selected in the listview.所以主要思想是在列表视图中选择项目时更改项目的背景颜色和文本颜色。

Here below you can see how I want the app to look like.在下面,您可以看到我希望该应用程序的外观。 我希望测验页面看起来像什么。

Here is my xaml file:这是我的 xaml 文件:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             NavigationPage.HasNavigationBar="false"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:quizApp"
             mc:Ignorable="d"
             
             x:Class="quizApp.quizpage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:SelectedToColorConverter x:Key="cnvInvert"></local:SelectedToColorConverter>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout>
            <StackLayout 
                x:Name="AppBar"
                HeightRequest="70"
                   WidthRequest="100"
                   HorizontalOptions="FillAndExpand"
                   VerticalOptions="Start"
                   
                   Padding="0, 20, 0, 0">
                <Label x:Name="TitleText"
               FontSize="32"
               TextColor="White"
               FontFamily="DMSans-Medium"
               HorizontalTextAlignment="Center"
               VerticalTextAlignment="Center" />
            </StackLayout>
            <StackLayout Padding="30,10,30,20">
                <Label Text="{Binding TitleText}"
               TextColor="#FABB05"
               FontSize="18"
               FontFamily="DMSans-Medium" />
                <Label Text="{Binding CurrentQuestionText}"
               TextColor="#213057"
               FontSize="22"
               FontFamily="DMSans-Medium" />
            </StackLayout>
            <StackLayout >
                <ListView x:Name="listView"  ItemsSource="{Binding CurrentOptions}" HasUnevenRows="True" SeparatorVisibility="None" SelectedItem="{Binding ChooseAnswer}" >        
                    <ListView.ItemTemplate >
                        <DataTemplate >
                            <ViewCell >
                                <StackLayout Padding="30,0,30,0" >
                                    <Frame
                                        VerticalOptions="Center"
                                        Margin="0,3,0,12"
                                        HorizontalOptions="FillAndExpand"
                                        HeightRequest="35"
                                        CornerRadius="5"  
                                        BackgroundColor="#FFFFFF"
                                        >

                                        <Label Text="{Binding .}"
                                               FontFamily="DMSans-Regular"
                                           FontSize="20"
                                           VerticalOptions="Center"
                                           HorizontalOptions="Center"
                                            TextColor="#000000">
                                        </Label>
                                    </Frame>
                                </StackLayout>
                            </ViewCell> 
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackLayout>
            <StackLayout Padding="30,0,30,30">
                <Button Text="{Binding CurrentButtonText}"
                Command="{Binding NextQuestion}"
                BackgroundColor="#4285F4"
                TextColor="White"
                HeightRequest="80"
                CornerRadius="5"
                HorizontalOptions="FillAndExpand"
                VerticalOptions="Center"
                FontSize="26"
                        TextTransform="None"
                FontFamily="DMSans-Medium" />
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

quizpage.xaml.cs file: quizpage.xaml.cs 文件:

using quizApp.Data_Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace quizApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]

    public partial class quizpage : ContentPage
    {
        public quizpage(string title, string color, List<QuizQuestion> questions)
        {

            InitializeComponent();
            BindingContext = new QuizPageModel(questions);
            TitleText.Text = title;
            AppBar.BackgroundColor = Color.FromHex(color);
        }


    }
}

And QuizPageModel.cs file:和 QuizPageModel.cs 文件:

using quizApp.Data_Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace quizApp
{
    public class QuizPageModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged([CallerMemberName] String name = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        


        // current chosen
        private int? _currentChosen;
        public int? CurrentChosen
        {
            get { return _currentChosen;  }
            set
            {
                _currentChosen = value;
                OnPropertyChanged();
            }
        }

        // current buttonText
        private string _currentButtonText;
        public string CurrentButtonText
        {
            get { return _currentButtonText; }
            set
            {
                _currentButtonText = value;
                OnPropertyChanged();
            }
        }

        // current question
        private string _currentQuestionText;
        public string CurrentQuestionText
        {
            get { return _currentQuestionText; }
            set 
            { 
                _currentQuestionText = value;
                OnPropertyChanged();
            }
        }

        // current options
        private string[] _currentoptions;
        public string[] CurrentOptions
        {
            get { return _currentoptions; }
            set
            {
                _currentoptions = value;
                OnPropertyChanged();
            }
        }

        // Current answer
        private int _currentAnswerValue;
        public int CurrentAnswerValue
        {
            get { return _currentAnswerValue; }
            set { _currentAnswerValue= value; OnPropertyChanged(); }
        }

        private int _totalQuestions;
        public int TotalQuestions
        {
            get
            { return _totalQuestions; }
            set
            {
                _totalQuestions = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(TitleText));
            }
        }


        // current Question number
        private int _currentQuestionNumber;
        public int CurrentQuestionNumber
        {
            get
            {
                return _currentQuestionNumber;
            }

            set
            {
                _currentQuestionNumber = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(TitleText));
            }
        }

        // choose item
        private string _chooseAnswer;
        public string ChooseAnswer
        {
            get { 
                
                return _chooseAnswer; }
            set
            {
                _chooseAnswer = value;
                OnPropertyChanged();
            }
        }

        // text 
        public string TitleText
        {
            get { return $"Question {_currentQuestionNumber}/{_totalQuestions}"; }
        }

        private int score;
        private int index;
        public Command NextQuestion { get; }
        public Command ChangeChosen { get; }

        public QuizPageModel(List<QuizQuestion> questions)
        {

            // initialise quiz values
            TotalQuestions = questions.Count;
            CurrentQuestionNumber= 1;
            score= 0;
            index = 0;
            ChooseAnswer = null;
            CurrentButtonText = "Next";

            // load first question
            LoadQuestion(questions);

            // NextQuestion function
            NextQuestion = new Command(async () =>
            {
                
                if (ChooseAnswer != null)
                {
                    CurrentChosen = Array.IndexOf(CurrentOptions, ChooseAnswer);

                    if (CurrentAnswerValue == CurrentChosen)
                    {
                        score++;
                    }
                    
                    if (index == TotalQuestions - 1)
                    {
                        await ShowResults();
                    }
                    else
                    {
                        CurrentQuestionNumber++;    
                        index++;
                        if (index == TotalQuestions - 1)
                        {
                            CurrentButtonText = "Finish";
                        }
                        LoadQuestion(questions);
                    }
                    
                    ChooseAnswer = null;
                    CurrentChosen = null;
                }
            });



            
        }

        private void LoadQuestion(List<QuizQuestion> questions)
        {
            CurrentQuestionText = questions[index].Question;
            CurrentAnswerValue = questions[index].Answer;
            CurrentOptions = questions[index].Options;
        }





        private async Task ShowResults() => await Application.Current.MainPage.Navigation.PushAsync(new finalpage(score, _totalQuestions, "80s Music Quiz", "#FABB05")).ConfigureAwait(false);

    }
}

You should look into visual state manager, you can include it inside your listview element in XAML.您应该查看可视化状态管理器,您可以将它包含在 XAML 中的 listview 元素中。 This is an example from MS.这是来自 MS 的示例。

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="CommonStates">
        <VisualState x:Name="Selected">
            <VisualState.Setters>
                <Setter Property="BackgroundColor" Value="Lime" />
            </VisualState.Setters>
        </VisualState>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM