Cristi Sandu
Cristi Sandu

Reputation: 13

NotifyCanExecuteChangedFor doesn't execute Command given, MVVM Community Toolkit .Net MAUI

I have a TimePicker and I try when the time change to call a command, but it doesn't work.

This is the code:

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(TimeSelectedCommand))]
TimeSpan startTime;

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(TimeSelectedCommand))]
TimeSpan endTime;

[RelayCommand]
private void TimeSelected()
{
    if (StartTime != null && EndTime != null && StartTime < EndTime)
    {
        Preview.NumberOfSelectedIntervals = (int)(EndTime.Hours - StartTime.Hours);
    }
}

An the code for XAML:

                <Border Style="{StaticResource TimePickerBorderStyle}">
                    <TimePicker Style="{StaticResource TimePickerStyle}"
                                Time="{Binding StartTime}" />
                </Border>
               
                <Border Grid.Column="2"
                        Style="{StaticResource TimePickerBorderStyle}">
                    <TimePicker Time="{Binding EndTime}"
                                Style="{StaticResource TimePickerStyle}" />
                </Border>

Upvotes: 1

Views: 4065

Answers (1)

Thiago Siqueira
Thiago Siqueira

Reputation: 36

I understand that you want to execute an action whenever startTime and/or endTime change. If that is not the case, update your question to clarify your goal.

The behavior described above can be achieved with:

[ObservableProperty]
TimeSpan startTime;

partial void OnStartTimeChanged(TimeSpan value)
{
    TimeSelected();
}

[ObservableProperty]
TimeSpan endTime;

partial void OnEndTimeChanged(TimeSpan value)
{
    TimeSelected();
}

private void TimeSelected()
{
    // your logic here.
}

OnStartTimeChanged and OnEndTimeChanged are partial methods.

See Running code upon changes.

Upvotes: 2

Related Questions