Prism:必须显式调用RaiseCanExecuteChanged()

时间:2016-08-15 15:47:17

标签: wpf mvvm prism delegatecommand

以下是一个非常简单的Prism.Wpf示例,其中DelegateCommand同时包含ExecuteCanExecute个代理人。

假设CanExecute取决于某些属性。看起来Prism的DelegateCommand在此属性更改时不会自动重新评估CanExecute条件,就像RelayCommand在其他MVVM框架中所做的那样。相反,您必须在属性设置器中显式调用RaiseCanExecuteChanged()。这会在任何非平凡的视图模型中导致大量重复代码。

有更好的方法吗?

视图模型

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>

2 个答案:

答案 0 :(得分:5)

正如@ l33t解释的那样,这是设计。如果希望DelegateCommand自动监视VM属性以进行更改,只需使用delegateCommand的ObservesProperty方法:

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

答案 1 :(得分:1)

这是设计的。这与性能有关。

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

另请参阅此answer

相关问题