简体   繁体   English

在ViewModel和Command之间进行通信

[英]Communicate between ViewModel and Command

Am creating a small cashier application, I have my CashViewModel having Sales filtred by Date . 我正在创建一个小型收银员应用程序,我的CashViewModel日期过滤销售额

now I've added a history button to show sales ( in a window ) grouped by date, then when a user selects a date my Date property changes, so i've binded that button to a RelayCommand. 现在我添加了一个历史按钮来显示按日期分组的销售( 在一个窗口中 ),然后当用户选择日期我的Date属性更改时,所以我将该按钮绑定到RelayCommand。

 public RelayCommand HistoryCommand
    {
        get
        {
            return _historyCommand
                ?? (_historyCommand = new RelayCommand(
                                      () =>
                                      {
                                          //?????????
                                      }));
        }
    }

My problem is inside the callback Action, i don't want to call a window directly from here and for testing reasons . 我的问题是在回调Action中, 我不想直接从这里调用窗口并出于测试原因。

should I use Messaging (if so should I create a message receiver, or is there other options ???) 我应该使用Messaging(如果是这样我应该创建一个消息接收器,还是有其他选项???)

You can create a WindowService (it call a window directly), and inject it into the view model. 您可以创建一个WindowService(它直接调用一个窗口),并将其注入视图模型。

For example: 例如:

public interface IWindowService
{
    Result ShowWindow(InitArgs initArgs);
}

public sealed class WindowService : IWindowService
{
    public Result ShowWindow(InitArgs initArgs);
    {
        //show window
        //return result
    }
}

public class CashViewModel 
{
    private IWindowService m_WindowService;

    public CashViewModel(IWindowService windowService)
    {
        m_WindowService = windowService;
    }

    public RelayCommand HistoryCommand
    {
        get
        {
            return _historyCommand
                ?? (_historyCommand = new RelayCommand(
                                      () =>
                                      {
                                          var result = m_WindowService.ShowWindow(args);
                                      }));
        }
    }
}

You can give function name there. 你可以在那里给出功能名称。

private ICommand _historyCommand;
public ICommand HistoryCommand
{
    get { return _historyCommand?? (_historyCommand= new RelayCommand(MyFunction)); }
}


private void MyFunction()
{
     // Function do something.
}

you may use EventAggregator implementation of Prism framework . 您可以使用EventAggregator实现Prism框架 It enables you to send and receive events without any knowledge of the sender and / or receivers. 它使您能够在不了解发送方和/或接收方的情况下发送和接收事件。

When you receive related event, you may just execute related code to display the view. 当您收到相关事件时,您可以只执行相关代码来显示视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM