[Xamarin Forms] Help on the dynamism of button and picker controls

camillecamille Member ✭✭
edited January 24 in Xamarin.Forms

Good evening, everyone,

First of all know that I am a beginner with xamarin and development on mobile platforms, I use the visual studio development environment with the C# language.

This is my problem:

I have created several buttons, I would like that depending on the buttons I click there are different elements in a picker.

For example: if I click on the North Pole button there are in the picker all the communes that concern the North Pole and if I click on the South Pole there are all the communes that concern this pole.

Do I make myself understood? If so, is that possible?

here is my code on the xaml side:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="PolQual.Views.StatementReferencielPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:PolQual.Views"
    xmlns:viewModels="clr-namespace:PolQual.ViewModels;assembly=PolQual"
    Title="Accueil">

    <ContentPage.BindingContext>
        <viewModels:StatementReferencielPageModel />
    </ContentPage.BindingContext>

    <ContentPage.Content>

        <StackLayout>

            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="8*" />
                    <RowDefinition Height="2*" />
                    <RowDefinition Height="40" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100*" />
                </Grid.ColumnDefinitions>

                <Label
                    Grid.Row="0"
                    Grid.Column="0"
                    FontSize="25"
                    HorizontalOptions="Center"
                    Text="Information sur le relevé référenciel" />

                <Label
                    x:Name="ErrorLabel"
                    Grid.Row="2"
                    Grid.Column="0"
                    FontSize="20"
                    HeightRequest="55"
                    HorizontalTextAlignment="Center"
                    TextColor="white"
                    VerticalTextAlignment="Center" />

            </Grid>

            <ScrollView>
                <Grid x:Name="gridLayout" />
            </ScrollView>

            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="2*" />
                    <RowDefinition Height="3*" />
                    <RowDefinition Height="8*" />
                    <RowDefinition Height="2*" />
                    <RowDefinition Height="3*" />
                    <RowDefinition Height="6*" />
                    <RowDefinition Height="3*" />
                    <RowDefinition Height="6*" />
                    <RowDefinition Height="3*" />
                    <RowDefinition Height="6*" />
                    <RowDefinition Height="2*" />
                    <RowDefinition Height="6*" />
                    <RowDefinition Height="1*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="25*" />
                    <ColumnDefinition Width="50*" />
                    <ColumnDefinition Width="25*" />
                </Grid.ColumnDefinitions>

                <Label
                    Grid.Row="1"
                    Grid.Column="1"
                    FontSize="15"
                    Text="Veuillez sélectioner le secteur :" />

                <Picker
                    x:Name="PickerSectorsLists"
                    Title="Sélectionner votre secteur"
                    Grid.Row="2"
                    Grid.Column="1"
                    ItemDisplayBinding="{Binding Value}"
                    ItemsSource="{Binding SectorsLists}"
                    SelectedItem="{Binding SelectedSector}" />

                <Label
                    Grid.Row="4"
                    Grid.Column="1"
                    FontSize="15"
                    Text="{Binding ShowHouseholdTrash}" />

                <Switch
                    x:Name="SwitchHousehodTrash"
                    Grid.Row="5"
                    Grid.Column="1"
                    HorizontalOptions="Start"
                    IsToggled="{Binding HouseholdTrash}" />

                <Label
                    Grid.Row="6"
                    Grid.Column="1"
                    FontSize="15"
                    Text="{Binding ShowBoxboard}" />

                <Switch
                    x:Name="SwitchBoxboard"
                    Grid.Row="7"
                    Grid.Column="1"
                    HorizontalOptions="Start"
                    IsToggled="{Binding Boxboard}" />

                <Label
                    Grid.Row="8"
                    Grid.Column="1"
                    FontSize="15"
                    Text="{Binding ShowGlass}" />

                <Switch
                    x:Name="SwitchGlass"
                    Grid.Row="9"
                    Grid.Column="1"
                    HorizontalOptions="Start"
                    IsToggled="{Binding Glass}" />

                <Button
                    Grid.Row="11"
                    Grid.Column="1"
                    BackgroundColor="#2196f3"
                    Clicked="GoToAssesmentGrid"
                    FontSize="20"
                    Text="Valider les informations"
                    TextColor="White" />

            </Grid>

        </StackLayout>

    </ContentPage.Content>
</ContentPage>

Behind C# side

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using PolQual.ViewModels;

namespace PolQual.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class StatementReferencielPage : ContentPage
    {
        private List<Pole> PolesLists { get; set; }

        public StatementReferencielPage()
        {
            InitializeComponent ();
            //BindingContext = new StatementReferencielPageModel();

            PolesLists = new List<Pole>
            {
                new Pole { Key = 1, Name = "Erdre et Cens", Color = "ffccd5"},
                new Pole { Key = 1, Name = "Erdre et Loire", Color = "ff4d4d"},
                new Pole { Key = 1, Name = "Loire-Sèvre et vignoble", Color = "ff9933"},
                new Pole { Key = 1, Name = "Sud-Ouest", Color = "bfbfbf"},
                new Pole { Key = 1, Name = "Loire-chézine", Color = "ffff4d"},
                new Pole { Key = 1, Name = "Nantes-Ouest", Color = "3385ff"},
                new Pole { Key = 1, Name = "Nantes-Loire", Color = "53c653"},
            };

            gridLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
            gridLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
            gridLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
            gridLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
            gridLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
            gridLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
            gridLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
            //collmun
            gridLayout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(25, GridUnitType.Star) });
            gridLayout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(50, GridUnitType.Star) });
            gridLayout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(25, GridUnitType.Star) });

            var PolesListsIndex = 0;

            for (int columnIndex = 1; columnIndex < 2; columnIndex++)
            {
                for (int rowIndex = 0; rowIndex < 7; rowIndex++)
                {
                    if (PolesListsIndex >= PolesLists.Count)
                    {
                        return;
                    }
                    var poles = PolesLists[PolesListsIndex];
                    PolesListsIndex += 1;

                    var button = new Button
                    {
                        Text = poles.Name,
                        BackgroundColor = Color.FromHex(poles.Color),
                        HorizontalOptions = LayoutOptions.Center,
                        VerticalOptions = LayoutOptions.Center,
                        WidthRequest = 280,
                    };
                    button.Clicked += async (object sender, EventArgs e) => await Navigation.PushAsync(new AssesmentGridPage());
                    gridLayout.Children.Add(button, columnIndex, rowIndex);
                }
            }
        }

        public void GoToAssesmentGrid(object sender, System.EventArgs e)
        {
            if (PickerSectorsLists.SelectedIndex == -1) 
            {
                ErrorLabel.BackgroundColor = Color.FromHex("ef5350");
                ErrorLabel.Text = "Veuillez sélectioner un secteur !";
                return;
            }
            else
            {
                var page = new AssesmentGridPage();
                Navigation.PushAsync(page);
                ErrorLabel.Text = null;
                ErrorLabel.BackgroundColor = Color.FromHex("#FFFFFF");
            }
         }

        public class Pole
        {
            public int Key { get; set; }
            public string Color { get; set; }
            public string Name { get; set; }
        }
    }
}

Posts

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    I am a beginner with xamarin and development

    That's fine. We were all new at one time.

    I would like that depending on the buttons I click there are different elements in a picker.

    Basic idea:
    The Picker source is binded to an ObservableCollection of items that will appear.
    If you want to change the items, just point the Picker at a different collection.

    However... There are huge issues with your code. The biggest being that you are doing all your coding in the C# code behind of the view - instead of in a ViewModel separated from the View. This completely violates the concept of MVVM design.

    It looks like you're trying to learn WHILE you're trying to architect a working application. This never goes well. Its like trying to learn how to design a house having no architecting experience so you just start hammering and cutting with the expectation that you'll figure it out as you go. Imagine what that house would be like.

    I'm going to suggest that for now you work on learning - not on trying to make an app.

    If you have no experience with MVVM design... no experience with databinding code to UI... etc. etc. then you need to first get a handle on that.

    Start with working the free textbook from cover to cover. Work it. Not just refer to it here and there.
    https://blogs.msdn.microsoft.com/microsoft_press/2016/03/31/free-ebook-creating-mobile-apps-with-xamarin-forms/

    Feel free to hit up on-line tutorials sites. There are plenty. Here's mine:

  • camillecamille Member ✭✭

    Thank you for your answer

    I'm going to dig on the CollectionObservable side.

    but I also use the view model, to make the link between my models (which I am setting up but for the moment I am focusing on my views). For the moment in my model views I put the list of my data.

    I used the behind code of my view to allow me to do things that I can't do in xaml. And it is in this behind code that I use my methods on events at the click of a button.

    This is my model view:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using System.Text;
    using Xamarin.Forms;
    
    namespace PolQual.ViewModels
    {
        class StatementReferencielPageModel : INotifyPropertyChanged
        {
            public List<Sector> SectorsLists { get; set; }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            void OnPropertyChanged([CallerMemberName] string propertyname = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
            }
    
            private bool _boxboard { get; set; }
            public bool Boxboard
            {
                get { return _boxboard; }
                set
                {
                    _boxboard = value;
                    OnPropertyChanged();
                    OnPropertyChanged(nameof(ShowBoxboard));
                }
            }
    
            private bool _glass { get; set; }
            public bool Glass
            {
                get { return _glass; }
                set
                {
                    _glass = value;
                    OnPropertyChanged();
                    OnPropertyChanged(nameof(ShowGlass));
                }
            }
    
            private bool _householdTrash { get; set; }
            public bool HouseholdTrash
            {
                get { return _householdTrash; }
                set
                {
                    _householdTrash = value;
                    OnPropertyChanged();
                    OnPropertyChanged(nameof(ShowHouseholdTrash));
                }
            }
    
            private Sector _selectedSector { get; set; }
            public Sector SelectedSector
            {
                get { return _selectedSector; }
                set
                {
                    if (_selectedSector != value)
                    {
                        _selectedSector = value;
                        // que faire quand l'élèment est sélectionné !
                    }
                }
            }
    
            public StatementReferencielPageModel()
            {
                SectorsLists = GetSectors().OrderBy(t => t.Key).ToList();
            }
    
            public List<Sector> GetSectors()
            {
                var Sectors = new List<Sector>()
                {
                    new Sector() { Key = 0, Value = "Coueron" },
                    new Sector() { Key = 1, Value = "Secteur 2" }
                };
                return Sectors;
            }
    
            public string ShowBoxboard
            {
                get
                {
                    return $"{(_boxboard ? "Jour de collecte des cartons : oui " : "Jour de collecte des cartons : non")}";
                }
            }
    
            public string ShowGlass
            {
                get
                {
                    return $"{(_glass ? "Jour de collecte du verre : oui " : "Jour de collecte du verre : non")}";
                }
            }
    
            public string ShowHouseholdTrash
            {
                get
                {
                    return $"{(_householdTrash ? "Jour de collecte des Ordure ménagère : oui " : "Jour de collecte des Ordure ménagère : non")}";
                }
            }
        }
    
        public class Sector
        {
            public int Key { get; set; }
            public string Value { get; set; }
        }
    }
    
Sign In or Register to comment.