Prism 3.命令
命令定义
public DelegateCommand SubmitCommand { get; private set; }
public ArticleViewModel()
{
SubmitCommand = new DelegateCommand<object>(Submit, CanSubmit);
}
void Submit(object parameter)
{
//implement logic
}
bool CanSubmit(object parameter)
{
return true;
}
public DelegateCommand SubmitCommand { get; private set; }
public ArticleViewModel()
{
SubmitCommand = new DelegateCommand(Submit, CanSubmit);
}
void Submit()
{
//implement logic
}
bool CanSubmit()
{
return true;
}
警告:使用值类型会造成问题(int, double, bool, etc),可以替换为Nullable
View中嵌入命令:
<Button Command="{Binding SubmitCommand}" CommandParameter="OrderId"/>
当绑定属性变化时,自动更新元素状态
private bool _isEnabled;
public bool IsEnabled
{
get { return _isEnabled; }
set
{
SetProperty(ref _isEnabled, value);
SubmitCommand.RaiseCanExecuteChanged();
}
}
ObservesProperty:当属性发生变化时,需要在命令中去通知界面属性改变需要使用ObservesProperty,通知命令状态改变,以通知UI状态更改
public class ArticleViewModel : BindableBase
{
private bool _isEnabled;
public bool IsEnabled
{
get { return _isEnabled; }
set { SetProperty(ref _isEnabled, value); }
}
public DelegateCommand SubmitCommand { get; private set; }
public ArticleViewModel()
{
SubmitCommand = new DelegateCommand(Submit, CanSubmit).ObservesProperty(() => IsEnabled);
}
void Submit()
{
//implement logic
}
bool CanSubmit()
{
return IsEnabled;
}
}
提示:可以注册多重观察属性
ObservesProperty(() => IsEnabled).ObservesProperty(() => CanSave).
ObservesCanExecute:如果CanExcute只是一个简单的bool的话,你可以用ObservesCanExecute去代替委托方法,这也可以去通知UI
private bool _isEnabled;
public bool IsEnabled
{
get { return _isEnabled; }
set { SetProperty(ref _isEnabled, value); }
}
public DelegateCommand SubmitCommand { get; private set; }
public ArticleViewModel()
{
SubmitCommand = new DelegateCommand(Submit, CanSubmit).ObservesCanExecute(() => IsEnabled);
}
void Submit()
{
//implement logic
}
警告:无法链式的注册ObservesCanExecute,对于CanExcute委托来说只能观察到一个属性
基于任务的DelegateCommand
基于ICommand是同步的,Excute和CanExcute也是,但是有两种方法去使用异步方法到命令中
1
public DelegateCommand SubmitCommand { get; private set; }
public ArticleViewModel()
{
SubmitCommand = new DelegateCommand(Submit);
}
async void Submit()
{
await SomeAsyncMethod();
}
2
public DelegateCommand SubmitCommand { get; private set; }
public ArticleViewModel()
{
SubmitCommand = new DelegateCommand(async ()=> await Submit());
}
Task Submit()
{
return SomeAsyncMethod();
}