I'm working on a WPF project using MVVM and I want to create a command for a DatePicker but I have no luck. I have this setup but it doesn't trigger the command on Date selection. What I want to do is when the user selects a date in the DatePicker, it'll trigger the command and call the function updateData() (in the DateSelectedCommand.cs). I can see that the command is triggered but updateData() is not called. I guess this line of code parameter is DateTime selected_date is wrong which causes the function not being executed.
I'm not sure how I can get the selected date and pass in updateData() as its argument.
Home.xaml
<DatePicker SelectedDate="{Binding SelectedDate}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedDateChanged">
<i:InvokeCommandAction Command="{Binding DateSelectedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</DatePicker>
HomeVM.cs
private DateTime _selectedDate;
public DateTime SelectedDate
{
get { return _selectedDate; }
set { _selectedDate = value; OnPropertyChanged(); }
}
public DateSelectedCommand DateSelectedCommand { get; set; }
//CONSTRUCTOR
public HomeVM(){
SelectedDate = DateTime.Today;
DateSelectedCommand = new DateSelectedCommand(this);
}
DateSelectedCommand.cs
using Dental_Practice_Monitor.Utilities;
using Dental_Practice_Monitor.ViewModel;
using System;
using System.Threading.Tasks;
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 async void Execute(object parameter)
{
if(parameter is DateTime selected_date)
{
VM.updateData(selected_date);
// (this is the function I want to call when user selects a date but it doesn't seem to work)
}
}
}
}
Updated 5/2/2023: I figured I could just use the SelectedDate property in HomeVM.cs instead of using the object parameter in DateSelectedCommand.cs.
It sounds like u have not initialized the DateSelectedCommand in your HomeVM-Constructor.