事件聚合器是解决此类问题的好方法。基本上有一个集中的类(为了简单起见,假设它是一个单例并且面对可能的反单例家伙的愤怒)负责将事件从一个对象转移到另一个对象。使用您的类名,用法可能如下所示:
public class MainViewModel
{
public MainViewModel()
{
WordAddedEvent event = EventAggregator.Instance.GetEvent<WordAddedEvent>();
event.Subscribe(WordAdded);
}
protected virtual void WordAdded(object sender WordAddedEventArgs e)
{
// handle event
}
}
public class AddWordViewModel
{
//From the command
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()
{
//return words
}
public void SaveWord(string word)
{
//Save word
if (WordAdded != null) WordAdded(this, new WordAddedEventArgs(word));
//Note that this way you lose the reference to where the word really came from
//probably doesn't matter, but might
}
}
public class MainViewModel
{
public MainViewModel()
{
//Add eventhandler to the services WordAdded event
}
}
您要避免做的是引入 ViewModel 之间的耦合,您将通过在一个 ViewModel 上与另一个 ViewModel 调用命令来创建该耦合,这将严重限制您扩展应用程序的选项(如果第二个 ViewModel 对新词感兴趣怎么办? ,现在 AddWordViewModel 也有责任告诉那个人吗?)