仅在访问页面时检查 CanExecute,而不是在属性更改时检查

问题描述 投票:0回答:1

这是我在 StackOverflow 上的第一个问题!

我正在使用 WinUI 和 .NET Community Toolkit MVVM 问题是 CanExecute on 按钮仅在访问 Page 时才会触发。我希望它在文本框中的每次击键时触发。我错过了什么吗?

查看:

<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>

查看型号:

    [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;
        }
    }

如果文本块不为空,我希望启用此按钮。我想在每次击键时验证它。然而,当文本框被填充时,它甚至无法失去焦点。我现在不知道该怎么办。我在 MVVM 方面并不是很先进。

c# mvvm winui-3 windows-community-toolkit
1个回答
0
投票

修改属性解决了我的问题:

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SendSmsCommand))]
private string nrTelefonu;
© www.soinside.com 2019 - 2024. All rights reserved.