在ViewModel(MVVM)中使用view方法

时间:2014-08-18 21:45:22

标签: c# wpf mvvm view viewmodel

让我们说我正在使用FlowDocumentPageViewer,我想使用find方法。 如何在遵循MVVM规则的同时使用它?我做了一些搜索,似乎解决方案是混合的。

有人建议您将View聚合到ViewModel,然后使用它来调用所需的方法:

例如:

private MainWindow mw; 

public MainWindowViewModel(MainWindow mw)
{
    this.mw = mw;
}

public void Find()
{
    mw.flowDocument.find();
}

但是其他人认为可以在视图中使用这些方法(Code-Behind),因为ViewModel不应该调用View特定的方法。

最后我听说过使用附加行为来解决这个问题,但我还没有广泛地查看该方法是否合适。

我真的不知道哪种方法是正确的,或者所有这些方法对于如何处理这种情况都是不正确的。如果你能给我一些关于哪种方法首选及其原因的见解,我将非常感激。

提前感谢您的回答。

1 个答案:

答案 0 :(得分:2)

我会用 MVVMLight messaging 之类的东西来解决这个问题。 (在Viewmodel中,您发送了一条消息,并在您注册此消息后的View代码中。)

Jesse Liberty of Microsoft有a great tutorial关于如何利用MVVM Light中的消息传递。

充当您的消息类型的类:

public class FlowDocumentFindMessage
{
   public string PageName { get; private set; }
   // or some other properties go here

   FlowDocumentFindMessage(string pageName){
          this.PageName = pageName
   }
}

新的查找,发送消息

public void Find()
{
    var msg = new FlowDocumentFindMessage("Page");
    Messenger.Default.Send<FlowDocumentFindMessage>( msg );
}

Code Behind,注册新消息

Messenger.Default.Register<GoToPageMessage>( this, ( action ) => ReceiveMessage( action ));

private object ReceiveMessage( FlowDocumentFindMessage action )
{
    //do some stuff
}