Prism:必须显式调用 RaiseCanExecuteChanged()

Prism: have to call RaiseCanExecuteChanged() explicitly

下面是一个非常简单的 Prism.Wpf 示例,其中 DelegateCommand 同时具有 ExecuteCanExecute 代表。

假设 CanExecute 依赖于某些 属性。似乎 Prism 的 DelegateCommand 不会在 属性 更改时自动重新评估 CanExecute 条件,就像 RelayCommand 在其他 MVVM 框架中所做的那样。相反,您必须在 属性 setter 中显式调用 RaiseCanExecuteChanged()。这会导致在任何重要的视图模型中出现大量重复代码。

有没有更好的方法?

ViewModel:

using System;
using Prism.Commands;
using Prism.Mvvm;

namespace PrismCanExecute.ViewModels
{
public class MainWindowViewModel : BindableBase
{
    private string _title = "Prism Unity Application";
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            SetProperty(ref _name, value);

            // Prism doesn't track CanExecute condition changes?
            // Have to call it explicitly to re-evaluate CanSubmit()
            // Is there a better way?
            SubmitCommand.RaiseCanExecuteChanged();
        }
    }
    public MainWindowViewModel()
    {
        SubmitCommand = new DelegateCommand(Submit, CanSubmit);
    }

    public DelegateCommand SubmitCommand { get; private set; }
    private bool CanSubmit()
    {
        return (!String.IsNullOrEmpty(Name));
    }
    private void Submit()
    {
        System.Windows.MessageBox.Show(Name);
    }

}
}

查看:

<Window x:Class="PrismCanExecute.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:prism="http://prismlibrary.com/"
    Title="{Binding Title}"
    Width="525"
    Height="350"
    prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
    <!--<ContentControl prism:RegionManager.RegionName="ContentRegion" />-->
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Name: " />
            <TextBox Width="150"
                     Margin="5"
                     Text="{Binding Name,  UpdateSourceTrigger=PropertyChanged}"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
            <Button Width="50"
                    Command="{Binding SubmitCommand}"
                    Content="Submit" Margin="10"/>
            <!--<Button Width="50"
                    Content="Cancel"
                    IsCancel="True" Margin="10"/>-->
        </StackPanel>
    </StackPanel>
</Grid>
</Window>

这是设计使然。与性能有关。

不过,您 可以 将 Prism DelegateCommand 替换为自定义命令来执行您想要的操作。例如。 this 实施似乎可以解决问题。但是,我不建议使用它。如果您有很多命令,您很可能会 运行 遇到性能问题。

另请参阅此 answer

正如@l33t 所解释的,这是故意的。如果您希望 DelegateCommand 自动监视 VM 属性的更改,只需使用 delegateCommand 的 ObservesProperty 方法:

var command = new DelegateCommand(Execute).ObservesProperty(()=> Name);