1

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>
2
  • 1) Any error message [that mentions StartTime, EndTIme, or TimeSelected] when compile, or in VS' Output pane when run? 2) Add to question the XAML that does {Binding StartTime} or EndTime, or other syntax. 3) Maybe the binding between View and ViewModel isn't set up. Add link to doc or example that you based this on? 4) What are the names of the View and ViewModel classes? Commented Aug 4, 2022 at 19:05
  • I don't have any errors in the console. The binding is set, values are changing for StartTime and EndTime. I put the command to a button and it works, only when I put on NotifyCanExecuteChangedFor doesn't run. Commented Aug 5, 2022 at 7:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.