Label show/hide binding is not working properly

Sadia Mustafa 5 Reputation points
2023-05-18T08:07:34.21+00:00

I want to hide or show label in SignUp by binding it from View Model by default all labels IsVisible property is false but even after setting it to true in view model, label are still not showing on screen. My SignUp page is actually a part of tabbed page.
Below is my complete xaml, xaml.cs and view model code:
TabbedPage

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Kainet.Views.SignInAndSignUp"
             xmlns:local="clr-namespace:Kainet.Views"
             Title="SignInAndSignUp"
             BarBackgroundColor="Black"
             BarBackground="Black"
             BarTextColor="White"
             SelectedTabColor="White"
             UnselectedTabColor="White">
    <local:SignIn Title="Sign In"/>
    <local:SignUp Title="Sign Up"/>
</TabbedPage>

SignUpViewModel

using Kainet.Models;
using Kainet.Services;
using LocalizationResourceManager.Maui.ComponentModel;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;

namespace Kainet.ViewModels
{
    public class SignUpViewModel : ObservableObject
    {
        public SignUpViewModel()
        {
            GetCountries();
            GetProvinces();
            GetGenders();
            DobViewModel dob = new DobViewModel();
            dobMonths = dob.Month;
            dobDays = dob.Day;
            dobYears = dob.Year;
            RegisterCommand = new Command(() => RegisterCommandAsync());
        }
        public ObservableCollection<Country> Countries { get; set; }
        public ObservableCollection<Province> Provinces { get; set; }
        public ObservableCollection<Gender> Genders { get; set; }
        public ObservableCollection<Years> dobYears { get; set; }
        public ObservableCollection<Days> dobDays { get; set; }
        public ObservableCollection<Months> dobMonths { get; set; }

        private Years _Year;
        public Years sYear
        {
            get { return _Year; }
            set
            {
                this._Year = value;
                if (String.IsNullOrEmpty(this._Year.Year))
                    IsDateOfBirthValid = true;
                if (!String.IsNullOrEmpty(this._Year.Year))
                    IsDateOfBirthValid = false;
                OnPropertyChanged();
            }
        }
        private Months _Month;
        public Months sMonth
        {
            get { return _Month; }
            set
            {
                this._Month = value;
                if (String.IsNullOrEmpty(this._Month.Month))
                    IsDateOfBirthValid = true;
                if (!String.IsNullOrEmpty(this._Month.Month))
                    IsDateOfBirthValid = false;
                OnPropertyChanged();
            }
        }
        private Days _Day;
        public Days sDay
        {
            get { return _Day; }
            set
            {
                this._Day = value;
                if (String.IsNullOrEmpty(this._Day.Day))
                    IsDateOfBirthValid = true;
                if (!String.IsNullOrEmpty(this._Day.Day))
                    IsDateOfBirthValid = false;
                OnPropertyChanged();
            }
        }

        private async void GetCountries()
        {
            Countries = new ObservableCollection<Country>();
            var data = await new CountriesService().GetCountriesAsync();
            Countries.Clear();
            foreach (var item in data)
            {
                Countries.Add(item);
            }
        }

        private async void GetProvinces()
        {
            Provinces = new ObservableCollection<Province>();
            var data = await new CountriesService().GetProvincesAsync();
            Provinces.Clear();
            foreach (var item in data)
            {
                Provinces.Add(item);
            }
        }

        private async void GetGenders()
        {
            Genders = new ObservableCollection<Gender>();
            var data = await new CountriesService().GetGendersAsync();
            Genders.Clear();
            foreach (var item in data)
            {
                Genders.Add(item);
            }
        }


        Regex hasCharacters = new Regex(@"^[a-zA-Z]+$");
        Regex hasNumber = new Regex(@"[0-9]+");

        //Name
        private bool _IsNameValid;
        public bool IsNameValid
        {
            get { return _IsNameValid; }
            set { _IsNameValid = value; OnPropertyChanged(); }
        }

        private string _Name;
        public string Name
        {
            get { return _Name; }
            set
            {
                this._Name = value;
                if (String.IsNullOrEmpty(this._Name) || !hasCharacters.IsMatch(this._Name))                    
                    IsNameValid = true;
                if (!String.IsNullOrEmpty(this._Name) && hasCharacters.IsMatch(this._Name))
                    IsNameValid = false;
                OnPropertyChanged();
            }
        }

        //Surname
        private bool _IsSurnameValid;
        public bool IsSurnameValid
        {
            get { return _IsSurnameValid; }
            set { _IsSurnameValid = value; OnPropertyChanged(); }
        }

        private string _Surname;
        public string Surname
        {
            get { return _Surname; }
            set
            {
                this._Surname = value;
                if (String.IsNullOrEmpty(this._Surname) || !hasCharacters.IsMatch(this._Surname))
                    IsSurnameValid = true;
                if (!String.IsNullOrEmpty(this._Surname) && hasCharacters.IsMatch(this._Surname))
                    IsSurnameValid = false;
                OnPropertyChanged();
            }
        }

        //Email
        private bool _IsEmailValid;
        public bool IsEmailValid
        {
            get { return _IsEmailValid; }
            set { _IsEmailValid = value; OnPropertyChanged(); }
        }

        private string _Email;
        public string Email
        {
            get { return _Email; }
            set
            {
                var EmailPattern = "^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@" + "[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
                this._Email = value;
                if (!String.IsNullOrEmpty(this._Email) && Regex.IsMatch(_Email, EmailPattern))
                    IsEmailValid = false;
                else
                    IsEmailValid = true;
                OnPropertyChanged();
            }
        }

        //Country

        private bool _IsCountryValid;
        public bool IsCountryValid
        {
            get { return _IsCountryValid; }
            set
            {
                _IsCountryValid = value;
                OnPropertyChanged();
            }
        }
        private Country _Country;
        public Country Country
        {
            get { return _Country; }
            set
            {
                _Country = value;
                if (this._Country.id == "")
                    IsCountryValid = true;
                if (this._Country.id != "")
                    IsCountryValid = false;
                OnPropertyChanged();
            }
        }

        //Province

        private bool _IsProvinceValid;
        public bool IsProvinceValid
        {
            get { return _IsProvinceValid; }
            set
            {
                _IsProvinceValid = value;
                OnPropertyChanged();
            }
        }
        private Province _Province;
        public Province Province
        {
            get { return _Province; }
            set
            {
                _Province = value;
                if (this._Province.id == 0)
                    IsProvinceValid = true;
                if (this._Province.id > 0)
                    IsProvinceValid = false;
                OnPropertyChanged();
            }
        }

        //Gender

        private bool _IsGenderValid;
        public bool IsGenderValid
        {
            get { return _IsGenderValid; }
            set
            {
                _IsGenderValid = value;
                OnPropertyChanged();
            }
        }
        private Gender _Gender;
        public Gender Gender
        {
            get { return _Gender; }
            set
            {
                _Gender = value;
                if (this._Gender.code == "")
                    IsGenderValid = true;
                if (this._Gender.code != "")
                    IsGenderValid = false;
                OnPropertyChanged();
            }
        }

        //City Name
        private bool _IsCityValid;
        public bool IsCityValid
        {
            get { return _IsCityValid; }
            set { _IsCityValid = value; OnPropertyChanged(); }
        }

        private string _City;
        public string City
        {
            get { return _City; }
            set
            {
                this._City = value;
                if (String.IsNullOrEmpty(this._City) || hasNumber.IsMatch(this._City))
                    IsCityValid = true;
                if (!String.IsNullOrEmpty(this._City) && !hasNumber.IsMatch(this._City))
                    IsCityValid = false;
                OnPropertyChanged();
            }
        }

        //Date of Birth
        private bool _IsDateOfBirthValid;
        public bool IsDateOfBirthValid
        {
            get { return _IsDateOfBirthValid; }
            set { _IsDateOfBirthValid = value; OnPropertyChanged(); }
        }

        //Password
        private bool _IsPasswordValid;
        public bool IsPasswordValid
        {
            get { return _IsPasswordValid; }
            set
            {
                _IsPasswordValid = value;
                OnPropertyChanged();
            }
        }

        private string _Password;
        public string Password
        {

            get { return _Password; }
            set
            {
                _Password = value;
                if (String.IsNullOrEmpty(this._Password))
                    IsPasswordValid = true;
                if (!String.IsNullOrEmpty(this._Password))
                    IsPasswordValid = false;
                OnPropertyChanged();
            }
        }

        //Presentation Code
        private bool _IsPreCodeValid;
        public bool IsPreCodeValid
        {
            get { return _IsPreCodeValid; }
            set
            {
                _IsPreCodeValid = value;
                OnPropertyChanged();
            }
        }

        private string _PreCode;
        public string PreCode
        {

            get { return _PreCode; }
            set
            {
                _PreCode = value;
                if (String.IsNullOrEmpty(this._PreCode))
                    IsPreCodeValid = true;
                if (!String.IsNullOrEmpty(this._PreCode))
                    IsPreCodeValid = false;
                OnPropertyChanged();
            }
        }

        public Command RegisterCommand { get; set; }
        private void RegisterCommandAsync()
        {
            if ((sYear != null) && (sMonth != null) && (sDay != null) && !String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Surname)
                && !String.IsNullOrEmpty(Email) && !String.IsNullOrEmpty(PreCode) && !String.IsNullOrEmpty(City) && !String.IsNullOrEmpty(Password) 
                && Country != null && Province != null && Gender != null)
            {
                int year = Int32.Parse(sYear.Year);
                int month = sMonth.MonthInNumber;
                int day = Int32.Parse(sDay.Day);
                int daysinmon = DateTime.DaysInMonth(year, month);
                if (day > daysinmon)
                {
                    IsDateOfBirthValid = true;
                }
                else if(IsNameValid == true)
                {

                }
                else if (IsSurnameValid == true)
                {

                }
                else if (IsEmailValid == true)
                {

                }
                else if (IsPasswordValid == true)
                {

                }
                else if (IsDateOfBirthValid == true)
                {

                }
                else if (IsPreCodeValid == true)
                {

                }
                else if (IsGenderValid == true)
                {

                }
                else if (IsCountryValid == true)
                {

                }
                else if (IsProvinceValid == true)
                {

                }
                else if (IsCityValid == true)
                {

                }
                else
                {
                    CreateUser model = new CreateUser();
                    model.Email = Email;
                    model.Password = Password;
                    model.Name = Name;
                    model.Surname = Surname;
                    model.Presentation_Code = PreCode;
                    model.Year_Of_Birth = Convert.ToInt32(sYear.Year);
                    model.Month_Of_Birth = sMonth.MonthInNumber;
                    model.Day_Of_Birth = Convert.ToInt32(sDay.Day);
                    model.Province = Province.id;
                    model.City = City;
                    model.Country = Country.id;
                    model.Gender = Gender.code;
                    model.Terms_And_Conditions = "Y";
                    new UserAccountService().CreateNewUser(model);
                }
            }
            else
            {
                if (String.IsNullOrEmpty(Name))
                    IsNameValid = true;
                if (String.IsNullOrEmpty(Surname))
                    IsSurnameValid = true;
                if (String.IsNullOrEmpty(Email))
                    IsEmailValid = true;
                if (String.IsNullOrEmpty(Password))
                    IsPasswordValid = true;
                if (String.IsNullOrEmpty(PreCode))
                    IsPreCodeValid = true;
                if (String.IsNullOrEmpty(City))
                    IsCityValid = true;
                if (sYear == null || sMonth == null || sDay==null)
                    IsDateOfBirthValid = true;
                if (Country == null)
                    IsCountryValid = true;
                if (Province == null)
                    IsProvinceValid = true;
                if (Gender == null)
                    IsGenderValid = true;
            }
        }
    }
}

SignUp.xaml.cs



namespace Kainet.Views;

public partial class SignUp : ContentPage
{
	public SignUp()
	{
        InitializeComponent();
        RegisterButton.IsEnabled = false;
    }
    public void SignUpPwdClicked(object sender, EventArgs args)
    {
        if (SignUpPwd.IsPassword)
        {
            SignUpPwdBtn.Glyph = "\uf070";
            SignUpPwd.IsPassword = false;
        }
        else
        {
            SignUpPwdBtn.Glyph = "\uf06e";
            SignUpPwd.IsPassword = true;
        }
    }

    public async void AgreeTermsBtnClicked(object sender, EventArgs args)
    {
        await Navigation.PushModalAsync(new WebViewPage());
    }

    private void CheckBox_CheckedChanged(object sender, CheckedChangedEventArgs e)
    {
        if (AgreeTermsCheck.IsChecked)
        {
            RegisterButton.IsEnabled = true;
        }
        else
        {
            RegisterButton.IsEnabled = false;
        }
    }

}

**
SignUp.xaml**

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Kainet.Views.SignUp"
             xmlns:loc="clr-namespace:LocalizationResourceManager.Maui;assembly=LocalizationResourceManager.Maui"
             xmlns:vm="clr-namespace:Kainet.ViewModels;assembly=Kainet"
             xmlns:ios="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls"
             Title="Sign Up"
             BackgroundColor="Black" 
             IconImageSource="signup.svg" 
             NavigationPage.HasNavigationBar="False">
    <ContentPage.Resources>
        <x:String x:Key="calendar">&#xf073;</x:String>
        <x:String x:Key="eye">&#xf06e;</x:String>
        <x:String x:Key="eyeslash">&#xf070;</x:String>
    </ContentPage.Resources>
    <ContentPage.BindingContext>
        <vm:SignUpViewModel/>
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <ScrollView>
            <VerticalStackLayout
            Spacing="10"
            Padding="30,0"
            VerticalOptions="Center">

                <VerticalStackLayout Margin="0,5,0,0">
                    <Label Text="{loc:Translate RegLabel}" TextColor="White" FontAttributes="Bold" FontSize="Title" HorizontalTextAlignment="Center"></Label>
                </VerticalStackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <Entry ios:Entry.CursorColor="Grey" Margin="15,0,0,0" Placeholder="{loc:Translate Name}" Text="{Binding Name}" Keyboard="Text" VerticalOptions="Center"></Entry>
                    </Frame>
                    <Label  IsVisible="{Binding IsNameValid}" Text="Invalid Name" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <Entry ios:Entry.CursorColor="Grey" Margin="15,0,0,0" Placeholder="{loc:Translate Surname}" Text="{Binding Surname}" Keyboard="Text" VerticalOptions="Center"></Entry>
                    </Frame>
                    <Label  IsVisible="{Binding IsSurnameValid}" Text="Invalid Surname" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <Entry ios:Entry.CursorColor="Grey" Margin="15,0,0,0" Placeholder="{loc:Translate Email}" Text="{Binding Email}" Keyboard="Email" VerticalOptions="Center"></Entry>
                    </Frame>
                    <Label  IsVisible="{Binding IsEmailValid}" Text="Invalid Email" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <VerticalStackLayout>
                            <Entry x:Name="SignUpPwd" ios:Entry.CursorColor="Grey" Margin="15,0,0,0" WidthRequest="300" Placeholder="{loc:Translate Password}" Text="{Binding Password}" IsPassword="True" Keyboard="Text" HorizontalOptions="StartAndExpand"></Entry>
                            <Button Margin="0,-45,0,0" Clicked="SignUpPwdClicked" TextColor="#ffffff" FontAttributes="Bold" HeightRequest="45" HorizontalOptions="End" BackgroundColor="#ffffff">
                                <Button.ImageSource>
                                    <FontImageSource x:Name="SignUpPwdBtn" Glyph="{StaticResource eye}"
                                    Color="#000000"
                                    Size="16"
                                    FontFamily="FAS"/>
                                </Button.ImageSource>
                            </Button>
                        </VerticalStackLayout>
                    </Frame>
                    <Label  IsVisible="{Binding IsPasswordValid}" Text="Invalid Password" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <!--<StackLayout Orientation="Horizontal">
                        <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                            <Entry ios:Entry.CursorColor="Grey" Margin="15,0,0,0" Placeholder="{loc:Translate Password}" IsPassword="True" Keyboard="Text"  VerticalOptions="Center"></Entry>
                        </Frame>
                    </StackLayout>-->

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <HorizontalStackLayout>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>
                            </Grid>
                            <Picker Grid.Column="0" Grid.Row="0" HorizontalOptions="Start" Margin="15,0,0,0" x:Name="YearPicker"  FontSize="14" Title="Year" WidthRequest="100" ItemDisplayBinding="{Binding Year}" ItemsSource="{Binding dobYears}"  SelectedItem="{Binding sYear}"/>
                            <Label Grid.Column="1" Grid.Row="0" Margin="0,10,0,0" Text="/"></Label>
                            <Picker Grid.Column="2" Grid.Row="0" HorizontalOptions="Center" Margin="5,0,0,0" x:Name="MonthPicker" FontSize="14" Title="Month"  WidthRequest="100"  ItemDisplayBinding="{Binding Month}" ItemsSource="{Binding dobMonths}" SelectedItem="{Binding sMonth}"/>
                            <Label Grid.Column="3" Grid.Row="0" Margin="0,10,0,0" Text="/"></Label>
                            <Picker Grid.Column="4" Grid.Row="0" HorizontalOptions="End" Margin="5,0,0,0"  x:Name="DayPicker" FontSize="14" Title="Day"  WidthRequest="100"  ItemDisplayBinding="{Binding Day}" ItemsSource="{Binding dobDays}"  SelectedItem="{Binding sDay}"/>
                        </HorizontalStackLayout>
                    </Frame>
                    <Label  IsVisible="{Binding IsDateOfBirthValid}" Text="Invalid Birth Date" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <Entry ios:Entry.CursorColor="Grey" Margin="15,0,0,0" Placeholder="{loc:Translate PreCode}" Text="{Binding PreCode}" Keyboard="Text" VerticalOptions="Center"></Entry>
                    </Frame>
                    <Label  IsVisible="{Binding IsPreCodeValid}" Text="Invalid Presentation Code" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <Picker Margin="15,0,0,0" Title="{loc:Translate Gender}" ItemsSource="{Binding Genders}" ItemDisplayBinding="{Binding description}" SelectedItem="{Binding Gender}"/>
                    </Frame>
                    <Label  IsVisible="{Binding IsGenderValid}" Text="Please Select Gender" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <Picker Margin="15,0,0,0" Title="{loc:Translate Country}" ItemsSource="{Binding Countries}" ItemDisplayBinding="{Binding name}" SelectedItem="{Binding Country}"/>
                    </Frame>
                    <Label  IsVisible="{Binding IsCountryValid}" Text="Please Select Country" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <Picker Margin="15,0,0,0" Title="{loc:Translate Province}" ItemsSource="{Binding Provinces}" ItemDisplayBinding="{Binding name}" SelectedItem="{Binding Province}"/>
                    </Frame>
                    <Label  IsVisible="{Binding IsProvinceValid}" Text="Please Select Province" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Vertical">
                    <Frame HeightRequest="45"  Padding="5,0,5,0" HasShadow="True" BorderColor="White" HorizontalOptions="FillAndExpand">
                        <Entry ios:Entry.CursorColor="Grey" Margin="15,0,0,0" Placeholder="{loc:Translate City}" Text="{Binding City}" Keyboard="Text" VerticalOptions="Center"></Entry>
                    </Frame>
                    <Label  IsVisible="{Binding IsCityValid}" Text="Invalid City" TextColor="Red"  FontSize="10" HorizontalTextAlignment="Center"/>
                </StackLayout>

                <StackLayout Orientation="Horizontal" HorizontalOptions="StartAndExpand">
                    <CheckBox x:Name="AgreeTermsCheck" CheckedChanged="CheckBox_CheckedChanged" Margin="0,-5,0,0"></CheckBox>
                    <Button Clicked="AgreeTermsBtnClicked" Margin="-10,-6,0,0" BackgroundColor="Black" TextColor="#ffffff" Text="{loc:Translate AcceptTerms}" BorderColor="Black"></Button>
                </StackLayout>

                <Button x:Name="RegisterButton" Command="{Binding RegisterCommand}" Margin="0,-5,0,0" TextColor="Black" FontAttributes="Bold" Text="{loc:Translate Register}" HeightRequest="45" HorizontalOptions="FillAndExpand" BackgroundColor="White"></Button>
            </VerticalStackLayout>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,216 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
789 questions
{count} votes