无法在 IEventAggregator 中重新设置 DelegateCommand?
Failed to re-set a DelegateCommand in IEventAggregator?
假设:
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
派生,如下所示。请参阅文档中的 Implementing 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!!"));
}
}
假设:
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
派生,如下所示。请参阅文档中的 Implementing 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!!"));
}
}