CanExecute is checked only when accessing Page, and not on property changed

36 views Asked by At

This is my first question on StackOverflow!

Im using WinUI with .NET Community Toolkit MVVM The problem is that CanExecute on button fires only when accessing Page. I want it to fire on every keystroke in the TextBox. Am i missing something?

View:

<TextBox x:Name="txt1" Text="{x:Bind ViewModel.NrTelefonu, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" MinWidth="300" Grid.Column="1" HorizontalAlignment="Left" Margin="20 0 0 0" />

<Button Command="{x:Bind ViewModel.SendSmsCommand}" Style="{StaticResource AccentButtonStyle}" Grid.Row="3" HorizontalAlignment="Right" Margin="20 20 0 0">
    <StackPanel Orientation="Horizontal" >
        <TextBlock Text="Wyƛlij SMS" FontSize="16" VerticalAlignment="Center"/>
        <FontIcon Glyph="&#xE8F3;" VerticalAlignment="Center" Margin="10 0 0 0" FontSize="25"/>
    </StackPanel>
</Button>

View Model:

    [ObservableProperty]
    private string nrTelefonu;

    [RelayCommand(CanExecute = nameof(CanSendSms))] 
    private void SendSms()
    {
       //sends SMS
    }

    private bool CanSendSms()
    {
        if (string.IsNullOrEmpty(NrTelefonu))
        {
            return false;
        }
        else
        {
            return true;
        }
    }

Im expecting to enable this button if textblock isn't empty. I would like to validate it one every keystroke. However it doesnt even work on losing focus when textbox is filled. I dont know what to do at this point. Im not extremely advanced in MVVM.

1

There are 1 answers

1
Revcio On

modifying property to this fixed my problem:

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SendSmsCommand))]
private string nrTelefonu;