DatePicker ICommand executed multiple times

54 Views Asked by At

I have a DatePicker with an ICommand which perform certain tasks. For some reason when I select a date, the VM.SetPreviousDate() method is called multiple times when the Icommand is executed (at least 3 times when I used breakpoints to debug). I was looking for solutions but no luck. Any help would be appreciated. Thank you!

HomeView.xaml

<DatePicker
     SelectedDate="{Binding SelectedDate}">
         <i:Interaction.Triggers>
              <i:EventTrigger EventName="SelectedDateChanged">
                   <i:InvokeCommandAction Command="{Binding DateSelectedCommand}" />
              </i:EventTrigger>
         </i:Interaction.Triggers>
</DatePicker>

DateSelectedCommand.cs:

using Dental_Practice_Monitor.ViewModel;
using System;
using System.Windows.Input;

namespace Dental_Practice_Monitor.Commands
{
    public class DateSelectedCommand : ICommand
    {
        public HomeVM VM { get; set; }
        public event EventHandler CanExecuteChanged;

        public DateSelectedCommand(HomeVM vm)
        {
            VM = vm;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            VM.SetPreviousDate(); // This gets called multiple times            
        }       
    }
}

HomeVM.cs

        private DateTime _selectedDate;
        public DateTime SelectedDate
        {
            get { return _selectedDate; }
            set { _selectedDate = value;
                OnPropertyChanged(); }
        }

// This method gets called multiple times
public void SetPreviousDate(); 

1

There are 1 best solutions below

1
alpha On BEST ANSWER

Why you are using both PropertyChanged and ICommand notifications? You can use the PropertyChanged notification to call your method SetPreviousDate() only one time as below:

XAML:

<DatePicker
     SelectedDate="{Binding SelectedDate}"
</DatePicker>

HomeVM.cs: private DateTime _selectedDate;

      public DateTime SelectedDate
        {
            get { return _selectedDate; }
            set { _selectedDate = value;
                  SetPreviousDate();
                  OnPropertyChanged(); }
        }


      public void SetPreviousDate();