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();
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:
HomeVM.cs: private DateTime _selectedDate;