22

在我的 WPF 应用程序中,我有 2 个 Windows(两个 Windows 都有自己的 ViewModel):

  1. 应用程序的主窗口,显示带有一堆单词的列表(绑定到 MainViewModel)

  2. 允许用户向列表中添加新项目的对话框窗口(绑定到 AddWordViewModel)

MainViewModel 具有 List 的 Articles 属性(此集合由服务类之一填充)绑定到主窗口的 ListBox

AddWordViewModel 有 SaveWordCommand 绑定到添加 Word 对话框的保存按钮。它的任务是获取用户输入的文本并将其传递给服务类。

用户点击保存按钮后,我需要通知 MainViewModel 从服务重新加载文章。

我的想法是在 MainViewModel 中公开公共命令并从 AddWordViewModel 执行它

实现它的正确方法是什么?

谢谢你!

4

1 回答 1

19

事件聚合器是解决此类问题的好方法。基本上有一个集中的类(为了简单起见,假设它是一个单例并且面对可能的反单例家伙的愤怒)负责将事件从一个对象转移到另一个对象。使用您的类名,用法可能如下所示:

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 也有责任告诉那个人吗?)

于 2009-04-28T17:42:49.257 回答