假设:
public DelegateCommand Cmd { get; private set; }
public ViewModel(IEventAggregtor ea)
{
_ea = ea;
Cmd = new DelegateCommand(() => Console.WriteLine("old!!"));
ea.GetEvent<TestEvent>().Subscribe(() => NewingCmd());
}
private void NewingCmd()
{
Cmd = new DelegateCommand(() => Console.WriteLine("new!!"));
}
预期:在事件发布之前,输出为“old!!”,而在发布之后,也意味着newingcmd
,输出为“new!!”。
但是在newingcmd
之前和之后,输出都是“old!!”。
那么,当我收到发布时,我可以更改delegateCommand
吗?
您没有实现inotifypropertychanged
,因此当将新的delegateCommand
分配给cmd
时,绑定不会收到更改通知,也不会更新。只需从Prism的bindablebase
派生,如下所示。请参见文档中的实现INotifyPropertyChanged。
public class ViewModel : BindableBase
{
private DelegateCommand _cmd;
public DelegateCommand Cmd
{
get => _cmd;
private set => SetProperty(ref _cmd, value);
}
public ViewModel(IEventAggregtor ea)
{
_ea = ea;
Cmd = new DelegateCommand(() => Console.WriteLine("old!!"));
ea.GetEvent<TestEvent>().Subscribe(() => NewingCmd());
}
private void NewingCmd()
{
Cmd = new DelegateCommand(() => Console.WriteLine("new!!"));
}
}