下面是一个非常简单的Prism.Wpf
示例,DelegateCommand
其中包含Execute
和CanExecute
代表。
假设这CanExecute
取决于某些属性。与其他 MVVM 框架一样,当此属性更改时,PrismDelegateCommand
似乎不会自动重新评估条件。相反,您必须在属性设置器中显式调用 RaiseCanExecuteChanged()。这会导致在任何重要的视图模型中出现大量重复代码。CanExecute
RelayCommand
有没有更好的办法?
视图模型:
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>