我正在学习棱镜。几个小时后我就遇到了一个问题,当订阅事件时,订阅方法没有被调用。我正在使用Prism和Autofac。
在下面的简化示例中,在MainViewModel Publish("dupa");事件中调用了ctor. 然后在按钮上单击UpdateWindow打开。在窗口的后端创建了UpdateViewModel的实例。
内部更新 VM ctor已运行,但在未执行 UpdateName 之后Subscribe(UpdateName);,由于某种我不明白的原因。
完整代码:
public class MainViewModel : ViewModelBase
{
private IEventAggregator _eventAggregator;
public MainViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator; //Prism
_eventAggregator.GetEvent<UpdateNameEvent>().Publish("dupa");
OnOpenCommand = new DelegateCommand(OnOpenWin);
}
public void OnOpenWin(object obj)
{
UpdateWindow win = new UpdateWindow();
win.Show();
}
public ICommand OnOpenCommand { get; private set; }
}
public class UpdateViewModel : ViewModelBase
{
private IEventAggregator _eventAggregator;
public UpdateViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator; //Prism
_eventAggregator.GetEvent<UpdateNameEvent>().Subscribe(UpdateName);
}
private void UpdateName(string name)
{
this.Name = name; //is not called at all
}
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
OnPropertyChanged();
}
}
}
public partial class UpdateWindow : Window
{
public UpdateWindow()
{
var bootStrapper = new BootStrapper();
var container = bootStrapper.BootStrap();
UpdateViewModel vm = container.Resolve<UpdateViewModel>();
InitializeComponent();
DataContext = vm;
}
}
一只萌萌小番薯
相关分类