when I go to the previous page, the color ofselected image is not displayed in the collection view

Viewed 39

I have three page.All pages have collection view and VieModels,on the third page I want to display read data.I created a collection view and wrote a label at the bottom to check if the data is read into a class object.My problem is that when I click the back button to return to the previous page, the data is stored in a class object (and that's good) but I want the selected image to have its changed background color, not return to its original state.

FIRST PAGE

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.Try.TryPage">
    <ContentPage.Content>
        <StackLayout>
            <CollectionView  x:Name="AddCar" ItemsSource="{Binding Hearts}"      
                  SelectionMode="None">
                <CollectionView.ItemsLayout>
                    <GridItemsLayout Orientation="Vertical"
                Span="2" />
                </CollectionView.ItemsLayout>
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Grid >
                            <Grid.RowDefinitions>
                                <RowDefinition Height="135" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="150" />
                                <ColumnDefinition Width="150" />
                            </Grid.ColumnDefinitions>
                            <Frame CornerRadius="10" BorderColor="Black" Padding="0" >
                                <Button 
                           CornerRadius="10" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="135" WidthRequest="150"
                         BackgroundColor="{Binding CustButtonColor}" ImageSource="{Binding Image}"
                          Command="{ Binding BindingContext.ChangeColor, 
                           Source={x:Reference Name=AddCar} }"  CommandParameter="{Binding .}"/>
                            </Frame>
                        </Grid>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
            <Label x:Name="small12" FontSize="Large" HorizontalOptions="Center"  VerticalOptions="Start"  Text="{Binding  tryHeart.TypeHeart}" />
            <Button Text="Navigate" Command="{Binding navigateCommand }"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

CODE BEHIND

namespace App1.Try
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TryPage : ContentPage
    {
        public TryPage()
        {
            InitializeComponent();
            BindingContext = new Try(Navigation);
        }
    }
}

View Model FIRST PAGE

namespace App1.Try
{
    class Try
    {
        public ObservableCollection<CircleColor> Hearts { get; set; }
        public ICommand ChangeColor { protected set; get;}

        public TryHeart tryHeart { get; set; }
        INavigation Navigation { get; set; }

        public Command navigateCommand { get; set; }
        public Command navigateCommand2 { get; set; }
        public async Task GotoPage2()
        {
           if(tryHeart.TypeHeart!=null) await Navigation.PushModalAsync(new Second(tryHeart));
        }
        public async Task GotoPage1()
        {
            await Navigation.PopModalAsync();
        }

        public Try(INavigation navigation)
        {
            tryHeart = new TryHeart();

            this.Navigation = navigation;
            this.navigateCommand = new Command(async () => await GotoPage2());
            this.navigateCommand2 = new Command(async () => await GotoPage1());

            Hearts = new ObservableCollection<CircleColor>();
            Hearts.Add(new CircleColor() { Name = "one",  Image = "heart", CustButtonColor = Color.White });
            Hearts.Add(new CircleColor() { Name = "two",  Image = "heart", CustButtonColor = Color.White });
            Hearts.Add(new CircleColor() { Name = "three",Image = "heart", CustButtonColor = Color.White });
            Hearts.Add(new CircleColor() { Name = "four", Image = "heart", CustButtonColor = Color.White });
      
            var DefaultCars = new ObservableCollection<CircleColor>();
            DefaultCars = Hearts;

            ChangeColor = new Command<CircleColor>((key) =>
            {
                foreach (var item in Hearts)
                {
                    item.CustButtonColor = Color.White;
                    item.Image = "heart";
                }
                var car = key as CircleColor;
                car.CustButtonColor = Color.LightCoral;
                tryHeart.TypeHeart = car.Name;
                
            });
        }

    }
}

SECOND PAGE

 <ContentPage.Content>
        <StackLayout>
            <StackLayout>
                <CollectionView  x:Name="AddCar" ItemsSource="{Binding Hearts}"      
                  SelectionMode="None">
                    <CollectionView.ItemsLayout>
                        <GridItemsLayout Orientation="Vertical"
                Span="2" />
                    </CollectionView.ItemsLayout>
                    <CollectionView.ItemTemplate>
                        <DataTemplate>
                            <Grid >
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="135" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="150" />
                                    <ColumnDefinition Width="150" />
                                </Grid.ColumnDefinitions>
                                <Frame CornerRadius="10" BorderColor="Black" Padding="0" >
                                    <Button 
                           CornerRadius="10" HorizontalOptions="Center" VerticalOptions="Center" HeightRequest="135" WidthRequest="150"
                         BackgroundColor="{Binding CustButtonColor}" ImageSource="{Binding Image}"
                          Command="{ Binding BindingContext.ChangeColor, 
                           Source={x:Reference Name=AddCar} }"  CommandParameter="{Binding .}"/>
                                </Frame>
                            </Grid>
                        </DataTemplate>
                    </CollectionView.ItemTemplate>
                </CollectionView>
                <Label x:Name="small12" FontSize="Large" HorizontalOptions="Center"  VerticalOptions="Start"  Text="{Binding  tryHeart.TypeHeart2}" />
                <Button Text="Navigate" Command="{Binding navigateCommand }"/>
                <Button Text="Back" Command="{Binding navigateCommand2 }"/>
            </StackLayout>

        </StackLayout>
    </ContentPage.Content>

CODE BEHIND

namespace App1.Try
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Second : ContentPage
    {
        public Second( TryHeart tryHeart)
        {
            InitializeComponent();
            BindingContext = new SSec(Navigation,tryHeart);
        }
    }
}

VIEW MODEL SECOND PAGE

namespace App1.Try
{
    class SSec
    {
       public ObservableCollection<CircleColor> Hearts { get; set; }
        public ICommand ChangeColor { protected set; get; }

        public TryHeart tryHeart { get; set; }
        INavigation Navigation { get; set; }

        public Command navigateCommand { get; set; }
        public Command navigateCommand2 { get; set; }
        public async Task GotoPage2()
        {
          if(tryHeart.TypeHeart2!=null) await Navigation.PushModalAsync(new Third(tryHeart));
        }

        public async Task GotoPage1()
        {
            await Navigation.PopModalAsync();
        }
        public SSec(INavigation navigation,TryHeart heart)
        {
            tryHeart = heart;

            this.Navigation = navigation;
            this.navigateCommand = new Command(async () => await GotoPage2());
            this.navigateCommand2 = new Command(async () => await GotoPage1());

            Hearts = new ObservableCollection<CircleColor>();
            Hearts.Add(new CircleColor() { Name = "oneO", Image = "heart", CustButtonColor = Color.White });
            Hearts.Add(new CircleColor() { Name = "twoO", Image = "heart", CustButtonColor = Color.White });
            Hearts.Add(new CircleColor() { Name = "threeO", Image = "heart", CustButtonColor = Color.White });
            Hearts.Add(new CircleColor() { Name = "fourO", Image = "heart", CustButtonColor = Color.White });

            var DefaultCars = new ObservableCollection<CircleColor>();
            DefaultCars = Hearts;

            ChangeColor = new Command<CircleColor>((key) =>
            {
                foreach (var item in Hearts)
                {
                    item.CustButtonColor = Color.White;
                    item.Image = "heart";
                }
                var car = key as CircleColor;
                car.CustButtonColor = Color.Orange;
                tryHeart.TypeHeart2 = car.Name;

            });
        }

    }
}

THIRD PAGE

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.Try.Third">
    <ContentPage.Content>
        <StackLayout>
              <Label x:Name="one" Text="{Binding  heart.TypeHeart}"  FontSize="Large" HorizontalOptions="Center"  VerticalOptions="Center"  />
        <Label x:Name="two" Text="{Binding  heart.TypeHeart2}" FontSize="Large" HorizontalOptions="Center"  VerticalOptions="Center"  />
        <Button Text="Back" Command="{Binding navigateCommand2 }"/>
          
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

CODE BEHIND

namespace App1.Try
{
    class Tht
    {
        public TryHeart heart { get; set; }
        INavigation Navigation { get; set; }

        public Command navigateCommand2 { get; set; }
        public async Task GotoPage1()
        {
            await Navigation.PopModalAsync();
        }
        public Tht(INavigation navigation, TryHeart h)
        {
            heart = h;
            this.Navigation = navigation;
            this.navigateCommand2 = new Command(async () => await GotoPage1());
           
        }
    }
}

VIEW MODEL THIRD PAGE

namespace App1.Try
{
    class Tht
    {
        public TryHeart heart { get; set; }
        INavigation Navigation { get; set; }

        public Command navigateCommand2 { get; set; }
        public async Task GotoPage1()
        {
            await Navigation.PopModalAsync();
        }
        public Tht(INavigation navigation, TryHeart h)
        {
            heart = h;
            this.Navigation = navigation;
            this.navigateCommand2 = new Command(async () => await GotoPage1());
           
        }
    }
}

Please help me to save color of selected item.Because in my project a person may want to go back and recheck all the information, and the selected elements are not visible (although in the object and recorded) enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

1 Answers

As you call Navigation.PopModalAsync() in your second page when you click back button(handle the GotoPage1 method),the second page will be destroyed,but the data tryHeart still exist.When you navigate to the second again,you could see the tryHeart.TypeHeart2 is shown,the page is recreated(so you could not see the selection on the UI).

Finally you could determine whether tryHeart.TypeHeart2 is empty and set the selection when you navigate to the second page.

For example in your second view model:

   public SSec(INavigation navigation,TryHeart heart)
    {
        tryHeart = heart;

        this.Navigation = navigation;
        this.navigateCommand = new Command(async () => await GotoPage2());
        this.navigateCommand2 = new Command(async () => await GotoPage1());

        Hearts = new ObservableCollection<CircleColor>();
        Hearts.Add(new CircleColor() { Name = "oneO", Image = "heart", CustButtonColor = Color.White });
        Hearts.Add(new CircleColor() { Name = "twoO", Image = "heart", CustButtonColor = Color.White });
        Hearts.Add(new CircleColor() { Name = "threeO", Image = "heart", CustButtonColor = Color.White });
        Hearts.Add(new CircleColor() { Name = "fourO", Image = "heart", CustButtonColor = Color.White });

        var DefaultCars = new ObservableCollection<CircleColor>();
        DefaultCars = Hearts;
        
        //determine 
        if(!string.IsNullOrEmpty(tryHeart.TypeHeart2)){
          if(tryHeart.TypeHeart2.Equals("oneO")){
              Hearts[0].CustButtonColor =  Color.Orange;
          }
          if(tryHeart.TypeHeart2.Equals("twoO")){
              Hearts[1].CustButtonColor =  Color.Orange;
          }
          if(tryHeart.TypeHeart2.Equals("threeO")){
              Hearts[2].CustButtonColor =  Color.Orange;
          }
          if(tryHeart.TypeHeart2.Equals("fourO")){
              Hearts[3].CustButtonColor =  Color.Orange;
          }
        }
        ChangeColor = new Command<CircleColor>((key) =>
        {
            foreach (var item in Hearts)
            {
                item.CustButtonColor = Color.White;
                item.Image = "heart";
            }
            var car = key as CircleColor;
            car.CustButtonColor = Color.Orange;
            tryHeart.TypeHeart2 = car.Name;

        });
    }
Related