将多个参数传递给Prism的EventAggregator

时间:2012-03-08 03:00:47

标签: wpf mvvm prism eventaggregator

我正在使用Prism的EventAggregator在我的模块的ViewModel之间进行松散耦合的通信。我在 ViewModelA 中有几个属性(例如FirstName,LastName),当它们的值发生更改时,需要更新 ViewModelB 中的属性。我目前的解决方案包括:

ViewModelA 使用FirstName的新值作为有效内容发布一个事件:

 public string FirstName
    {
        get {return firstName;}
        set 
        {
            this.firstName = value;
            eventAggregator.GetEvent<PatientDetailsEvent>().Publish(firstName);
        }
    }

ViewModelB 订阅了Event并相应地更改了其FirstName属性:

public PatientBannerViewModel(IEventAggregator eventAggregator)
    {
        this.eventAggregator = eventAggregator;
        eventAggregator.GetEvent<PatientDetailsEvent>().Subscribe(UpdateBanner, ThreadOption.UIThread);
    }

    public void UpdateBanner(string firstName)
    {
        this.FirstName = firstName;
    }

这适用于单个属性。它不适用于多个不同的属性,因为 ViewModelB 不知道 ViewModelA 上的哪个属性已更改。 ViewModelB知道新值是什么,但它不知道要更新哪个属性。

我可以为每个属性创建单独的事件,但这似乎是重复的。只使用一个事件似乎更干净。理想情况下,在发布事件时,ViewModelA应该告诉ViewModelB哪个属性已更改。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:5)

抱歉,我在this post找到了我的问题的答案。 Rachel Lim的This blog post也很有帮助。

我们需要 ViewModelA (发布商)告诉 ViewModelB (订阅者)两条信息:

  1. ViewModelA
  2. 上更改了哪些属性
  3. 此属性的新值是什么
  4. 我们需要传达2条信息(即属性),但Prism的EventAggregator只接受一个参数payload。这就是问题所在。

    要通过EventAggregator传递多条信息( properties ),您可以发布将类定义为EventAggregator payload的类的实例。我调用了这个类PatientDetailsEventParameters,它定义了两个属性:

    public class PatientDetailsEventParameters
    {
        public string PatientProperty { get; set; }
        public string Value { get; set; }
    }
    

    我在基础架构程序集(我定义事件的同一个地方)中创建了这个类,我的所有其他程序集都引用了它。

    然后,您可以将此类的实例发布为有效内容(而不是仅包含1个值的字符串)。这允许将多个参数传递到有效载荷中。

    public string FirstName
        {
            get 
            {
                return firstName;
            }
            set 
            {
                this.firstName = value;
                eventAggregator.GetEvent<PatientDetailsEvent>().Publish(new PatientDetailsEventParameters() {Value = firstName, PatientProperty = "firstName"});
            }
        }
    

    您可以在此处看到PatientDetailsEventParameters发布时我的PatientDetailsEvent的新实例已创建。还设置了两个属性ValuePatientPropertyPatientProperty是一个字符串,用于告知 ViewModelB (即订阅者)已更改的属性。 Value是已更改的属性的新值。