事件聚合器是解决这种问题的一种很好的方式。基本上,有一个中央类(为了简单起见,我们假设它是一个Singleton,并面对反对Singleton的人可能会带来的愤怒),负责将事件从一个对象传递到另一个对象。使用您的类名,使用可能如下:
public class MainViewModel
{
public MainViewModel()
{
WordAddedEvent event = EventAggregator.Instance.GetEvent<WordAddedEvent>();
event.Subscribe(WordAdded);
}
protected virtual void WordAdded(object sender WordAddedEventArgs e)
{
}
}
public class AddWordViewModel
{
public void ExecuteAddWord(string word)
{
WordAddedEvent event = EventAggregator.Instance.GetEvent<WordAddedEvent>();
event.Publish(this, new WordAddedEventArgs(word));
}
}
这种模式的优点是,您可以非常轻松地扩展应用程序以创建多种单词,并且对已添加的单词感兴趣的多个ViewModel,两者之间没有耦合,因此您可以根据需要添加和删除它们。
如果你想避免单例模式(我建议你这样做以进行测试),那么值得考虑依赖注入,不过这确实是另一个问题。
好的,最后一点想法。我从重新阅读你的问题中看到,你已经有了某种处理Word对象的Word Service类来处理检索和存储。由于两个ViewModel已经与该服务耦合,因此该服务可以负责在添加新单词时引发事件。尽管我仍然建议EventAggregator更灵活且更好,但是YAGNI可能适用于此处。
public class WordService
{
public event EventHandler<WordAddedEventArgs> WordAdded;
public List<string> GetAllWords()
{
}
public void SaveWord(string word)
{
if (WordAdded != null) WordAdded(this, new WordAddedEventArgs(word));
}
}
public class MainViewModel
{
public MainViewModel()
{
}
}
但是你要避免的是,在一个ViewModel上调用另一个ViewModel的命令,这会导致ViewModel之间的耦合,严重限制了扩展应用程序的选项(如果第二个ViewModel对新单词感兴趣,现在AddWordViewModel负责告诉它吗?)