CanExecute方法未激发



我正在使用WinUI MVVM(作为MVVM新手(

这是我在XAML 中的按钮

<Button Grid.Row="0"  Content="Create New" Width="100" Margin="5"
Command="{x:Bind ViewModel.CreateNewCommand }" 
Visibility="{x:Bind ViewModel.IsCreateNewVisible, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

在ViewModel的构造函数中,我有这样的连接:

CreateNewCommand = new RelayCommand(Handle_CreateNewCommand, CanExecuteCreateNew);

这是CanExecute方法:

public bool CanExecuteCreateNew()
{
return IsCreateNewEnabled;
}
private bool _isCreateNewEnabled = false;
public bool IsCreateNewEnabled
{
get => _isCreateNewEnabled;
set
{
SetProperty(ref _isCreateNewEnabled, value);
}
}

如果我在VM构造函数中分配IsCreateNewEnabled属性,它将正确呈现、启用或禁用。

当我单击按钮时,它会触发处理程序方法,在执行该方法中的一行代码之前,它会激发值为true的canExecute方法。在处理程序方法中,我将IsCreateNewEnabled设置为false,但这对按钮没有影响,也不会激发CanExecute方法。

有什么想法吗?

感谢

卡尔

您可以使用CommunityToolkit.MvvmNuGet包以这种方式执行此操作。

ViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace Mvvm;
// This class needs to be "partial" for the CommunityToolkit.Mvvm.
public partial class YourViewModel : ObservableObject
{
[RelayCommand(CanExecute = nameof(CanCreateNew))]
// A "CreateNewCommand" command will be auto-generated.
private void CreateNew()
{
}
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(CreateNewCommand))]
// A "CanCreateNew" property that
// notifies the "CreateNewCommand" to update its availability
// will be auto-generated.
private bool canCreateNew = false;
}

主窗口.xaml.cs

using Microsoft.UI.Xaml;
namespace Mvvm;
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
public YourViewModel ViewModel { get; } = new();
}

主窗口.xaml

<Window
x:Class="Mvvm.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel>
<Button
Command="{x:Bind ViewModel.CreateNewCommand}"
Content="Create New" />
<ToggleButton
Content="Can create new"
IsChecked="{x:Bind ViewModel.CanCreateNew, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Window>

最新更新