Delete button inside ListView

I had created a listView with a Delete button inside it. But When I click on Delete button it doesn't fires? What can be the reason.

Best Answer

  • GeetSGeetS US ✭✭✭
    edited July 2017 Accepted Answer

    Thanks everyone for replying. Below link explains how to access parameter.
    https://stackoverflow.com/questions/40913439/xamarin-forms-button-command-binding-inside-a-listview
    Based on these 2 links, I had implemented listview with button as below:
    1. In NotificationPage.xaml defined listview with delete button as below:
    ContentPage.Resources
    ResourceDictionary
    Style x:Key="DelFormat" TargetType="Button"
    Setter Property="TextColor" Value="#FFFFFF"
    Setter Property="BackgroundColor" Value="#ff0000"
    Setter Property="HeightRequest" Value="35"
    Setter Property="FontSize" Value="10"
    Setter Property="HorizontalOptions" Value="End"
    Style
    ResourceDictionary E
    ContentPage.Resources E

        StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand"           
            StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand"                
                ListView x:Name="lstNotification" ItemsSource="{Binding NotifyEmails}" HasUnevenRows="False"
                ListView.ItemTemplate
                    DataTemplate
                        ViewCell
                                StackLayout
                                    Grid x:Name="Item" Padding="2"
                                        Grid.ColumnDefinitions
                                            ColumnDefinition Width="1*" 
                                            ColumnDefinition Width="1*" 
                                        Grid.ColumnDefinitions
                                        Label Text="{Binding .}" FontSize="14" Grid.Column="0"
                                        Button Text="Delete" Command="{Binding DeleteClicked}" Style="{StaticResource DelFormat}" Grid.Column="1" 
                 BindingContext="{Binding Source={x:Reference lstNotification}, Path=BindingContext}"
                                                CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"
                                    Grid E
                                StackLayout E
                            ViewCell E
                    DataTemplate E
                ListView.ItemTemplate E
            ListView E
        StackLayout E
        StackLayout E
    
    1. In NotificationPage.xaml.cs,
      public NotificationViewModel NotificationViewModel { get; set; }

      public NotificationPage(TicketCase tc)
      {
          InitializeComponent();
          BindingContext = new NotificationViewModel(tc);           
      }
      
    2. In NotificationViewModel.cs
      public class NotificationViewModel : BaseViewModel
      {
      private TicketCase _ticketCase;
      private string _emailId;
      private ObservableRangeCollection _NotifyEmails;

      public TicketCase TicketCase
      {
          get { return _ticketCase; }
          set
          {
              _ticketCase = value;
              OnPropertyChanged();
          }
      }       
      
      public string EmailId
      {
          get { return _emailId; }
          set
          {
              _emailId = value;
              OnPropertyChanged();
          }
      }
      
      public ObservableRangeCollection<string> NotifyEmails
      {
          get { return _NotifyEmails; }
          set
          {
              _NotifyEmails = value;
              OnPropertyChanged();
          }
      }
      
      public RelayCommand<TicketCase> AddNotificationCommand { get; private set; }
      public NotificationViewModel(TicketCase tc)
      {
          try
          {
              if (tc != null && tc.Notifications != null)
              {
                  this.TicketCase = tc;
                  NotifyEmails = null;
                  NotifyEmails = new ObservableRangeCollection<string>();
                  foreach (Notifications nf in tc.Notifications)
                  {
                      NotifyEmails.Add(nf.EmailId);
                  }                    
              }
              AddNotificationCommand = new RelayCommand<TicketCase>(parameter => AddNotification(parameter));
          }
          catch (Exception ex)
          { }
      }
      
      public async void AddNotification(TicketCase tc)
      {
          if (!string.IsNullOrWhiteSpace(EmailId) && IsValidEmail())
          {
              Notifications nf = new Notifications();
              nf.TicketCaseId = TicketCase.TicketCaseId;
              nf.EmailId = EmailId;
              nf.CreatedBy = IdentityHelper.Users.UsersId;
              nf.CreatedOn = DateTime.Now;
              var tcc = new TicketCaseClient();
              var result = await tcc.AddNotification(nf);  //Check & Add Email in DB
              if (result > 0)
              {                   
                  await Application.Current.MainPage.DisplayAlert("Notification", "Notification Added Successfully.", "Ok");
                  EmailId = string.Empty;
              }
              else
              {
                  await App.Current.MainPage.DisplayAlert("Notification", "Email already Exists!!! Please specify another Email ID.", "Ok");
              }
          }
          else
          {
              await App.Current.MainPage.DisplayAlert("Notification", "Please enter a valid Email.", "Ok");
          }
      }
      
      public Command DeleteClicked
      {
          get
          {
              return new Command(async (e) =>
              {
                  var itm = e as string;
                  var rst = await App.Current.MainPage.DisplayAlert("Notification", "Are you sure you want to Delete " + itm +"???", "Yes","No");
                  if (rst)
                  {
                      var tClnt = new TicketCaseClient();
                      Notifications nf = new Notifications();
                      nf.TicketCaseId = TicketCase.TicketCaseId;
                      nf.EmailId = itm;
                      var result = await tClnt.DeleteNotification(nf);
                      if (result > 0)
                      {
                          await App.Current.MainPage.DisplayAlert("Notification", "Deleted Successfully.", "Ok");
                      }
                      else
                          await App.Current.MainPage.DisplayAlert("Notification", "Sorry!!! Due to some issue record can't be Deleted.", "Ok");
                  }
              });
          }
      }
      
      private bool IsValidEmail()
      {
          Boolean IsValid = false;
          if (EmailId != null)
          {
              const string emailRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
         @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
              IsValid = Regex.IsMatch(EmailId, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
          }
          return IsValid;
      }      
      

      }

Answers

  • HunumanHunuman GBMember ✭✭✭✭

    Hi @GeetS

    Looking closely in to my crystal ball I see that line 47 is incorrect.

    If that doesn't work may be we need to see the code after all...

    :)

    Tim

  • GeetSGeetS USMember ✭✭✭

    I had solved it as explained here: https://techsolutions2017.blogspot.in/2017/01/listview-in-xamarin-forms-in-mvvm.html#comment-form

    But now my query is how to access commandparameter(defined in xaml) inside Command(defined in viewmodel)

  • HunumanHunuman GBMember ✭✭✭✭

    @GeetS

    This excellent blog post by @DavidBritch covers commanding and parameters.

    If that does not help, let us know.

    Tim

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    @GeetS said:
    I had solved it as explained here: https://techsolutions2017.blogspot.in/2017/01/listview-in-xamarin-forms-in-mvvm.html#comment-form

    But now my query is how to access commandparameter(defined in xaml) inside Command(defined in viewmodel)

    this post is very useful

  • GeetSGeetS USMember ✭✭✭
    edited July 2017 Accepted Answer

    Thanks everyone for replying. Below link explains how to access parameter.
    https://stackoverflow.com/questions/40913439/xamarin-forms-button-command-binding-inside-a-listview
    Based on these 2 links, I had implemented listview with button as below:
    1. In NotificationPage.xaml defined listview with delete button as below:
    ContentPage.Resources
    ResourceDictionary
    Style x:Key="DelFormat" TargetType="Button"
    Setter Property="TextColor" Value="#FFFFFF"
    Setter Property="BackgroundColor" Value="#ff0000"
    Setter Property="HeightRequest" Value="35"
    Setter Property="FontSize" Value="10"
    Setter Property="HorizontalOptions" Value="End"
    Style
    ResourceDictionary E
    ContentPage.Resources E

        StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand"           
            StackLayout Orientation="Vertical" VerticalOptions="FillAndExpand"                
                ListView x:Name="lstNotification" ItemsSource="{Binding NotifyEmails}" HasUnevenRows="False"
                ListView.ItemTemplate
                    DataTemplate
                        ViewCell
                                StackLayout
                                    Grid x:Name="Item" Padding="2"
                                        Grid.ColumnDefinitions
                                            ColumnDefinition Width="1*" 
                                            ColumnDefinition Width="1*" 
                                        Grid.ColumnDefinitions
                                        Label Text="{Binding .}" FontSize="14" Grid.Column="0"
                                        Button Text="Delete" Command="{Binding DeleteClicked}" Style="{StaticResource DelFormat}" Grid.Column="1" 
                 BindingContext="{Binding Source={x:Reference lstNotification}, Path=BindingContext}"
                                                CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"
                                    Grid E
                                StackLayout E
                            ViewCell E
                    DataTemplate E
                ListView.ItemTemplate E
            ListView E
        StackLayout E
        StackLayout E
    
    1. In NotificationPage.xaml.cs,
      public NotificationViewModel NotificationViewModel { get; set; }

      public NotificationPage(TicketCase tc)
      {
          InitializeComponent();
          BindingContext = new NotificationViewModel(tc);           
      }
      
    2. In NotificationViewModel.cs
      public class NotificationViewModel : BaseViewModel
      {
      private TicketCase _ticketCase;
      private string _emailId;
      private ObservableRangeCollection _NotifyEmails;

      public TicketCase TicketCase
      {
          get { return _ticketCase; }
          set
          {
              _ticketCase = value;
              OnPropertyChanged();
          }
      }       
      
      public string EmailId
      {
          get { return _emailId; }
          set
          {
              _emailId = value;
              OnPropertyChanged();
          }
      }
      
      public ObservableRangeCollection<string> NotifyEmails
      {
          get { return _NotifyEmails; }
          set
          {
              _NotifyEmails = value;
              OnPropertyChanged();
          }
      }
      
      public RelayCommand<TicketCase> AddNotificationCommand { get; private set; }
      public NotificationViewModel(TicketCase tc)
      {
          try
          {
              if (tc != null && tc.Notifications != null)
              {
                  this.TicketCase = tc;
                  NotifyEmails = null;
                  NotifyEmails = new ObservableRangeCollection<string>();
                  foreach (Notifications nf in tc.Notifications)
                  {
                      NotifyEmails.Add(nf.EmailId);
                  }                    
              }
              AddNotificationCommand = new RelayCommand<TicketCase>(parameter => AddNotification(parameter));
          }
          catch (Exception ex)
          { }
      }
      
      public async void AddNotification(TicketCase tc)
      {
          if (!string.IsNullOrWhiteSpace(EmailId) && IsValidEmail())
          {
              Notifications nf = new Notifications();
              nf.TicketCaseId = TicketCase.TicketCaseId;
              nf.EmailId = EmailId;
              nf.CreatedBy = IdentityHelper.Users.UsersId;
              nf.CreatedOn = DateTime.Now;
              var tcc = new TicketCaseClient();
              var result = await tcc.AddNotification(nf);  //Check & Add Email in DB
              if (result > 0)
              {                   
                  await Application.Current.MainPage.DisplayAlert("Notification", "Notification Added Successfully.", "Ok");
                  EmailId = string.Empty;
              }
              else
              {
                  await App.Current.MainPage.DisplayAlert("Notification", "Email already Exists!!! Please specify another Email ID.", "Ok");
              }
          }
          else
          {
              await App.Current.MainPage.DisplayAlert("Notification", "Please enter a valid Email.", "Ok");
          }
      }
      
      public Command DeleteClicked
      {
          get
          {
              return new Command(async (e) =>
              {
                  var itm = e as string;
                  var rst = await App.Current.MainPage.DisplayAlert("Notification", "Are you sure you want to Delete " + itm +"???", "Yes","No");
                  if (rst)
                  {
                      var tClnt = new TicketCaseClient();
                      Notifications nf = new Notifications();
                      nf.TicketCaseId = TicketCase.TicketCaseId;
                      nf.EmailId = itm;
                      var result = await tClnt.DeleteNotification(nf);
                      if (result > 0)
                      {
                          await App.Current.MainPage.DisplayAlert("Notification", "Deleted Successfully.", "Ok");
                      }
                      else
                          await App.Current.MainPage.DisplayAlert("Notification", "Sorry!!! Due to some issue record can't be Deleted.", "Ok");
                  }
              });
          }
      }
      
      private bool IsValidEmail()
      {
          Boolean IsValid = false;
          if (EmailId != null)
          {
              const string emailRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
         @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
              IsValid = Regex.IsMatch(EmailId, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
          }
          return IsValid;
      }      
      

      }

Sign In or Register to comment.