簡體   English   中英

為什么在使用 Prism EventAggregator 時不調用我的 Subscribe 方法?

[英]Why my Subscribe method is not called when using Prism EventAggregator?

我正在學習棱鏡。 幾個小時以來,我遇到了一個問題,訂閱事件時,訂閱方法沒有被調用。 我正在使用PrismAutofac

在下面的簡化示例中,在MainViewModel Publish("dupa"); 事件在ctor被調用。 並在按鈕上單擊UpdateWindow打開。 在窗口的后端創建了UpdateViewModel 的實例。

更新 VM ctor內部運行,但在Subscribe(UpdateName); 由於某些我不明白的原因,未執行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;
        }
    }

更新

經過調查,我注意到,當訂閱這樣的事件時,它工作正常:

Utility.EventAggregator.GetEvent<UpdateNameEvent>().Subscribe(UpdateName);

訂閱使用過的注入eventAggregator 時,它不起作用:

_eventAggregator.GetEvent<UpdateNameEvent>().Subscribe(UpdateName);

EventAggregatorAutofac注冊如下:

builder.RegisterType<EventAggregator>()
        .As<IEventAggregator>().SingleInstance();

我不明白為什么這種依賴不起作用?

我不明白為什么這種依賴不起作用?

因為你創建一個新的EventAggregatorUpdateViewModel

var bootStrapper = new BootStrapper();
var container = bootStrapper.BootStrap();
UpdateViewModel vm = container.Resolve<UpdateViewModel>();

這看起來好像是為UpdateWindow創建了一個新容器,並且新容器將有一個新的 - 即不同的 - EventAggregator 當然,這兩者不會相互發送事件。

因此,解決方案是使用一個容器來解決您的所有問題。 這就是使用靜態Utility時發生的情況。 您應該避免使用這樣的服務定位器。 看看ViewModelLocator ,它可以很容易地為給定的視圖創建視圖模型,例如,或者在創建時將容器傳遞給UpdateWindow (雖然也有點丑陋)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM