S3ddi9
S3ddi9

Reputation: 2151

Communicate between ViewModel and Command

Am creating a small cashier application, I have my CashViewModel having Sales filtred by Date.

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.

 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 .

should I use Messaging (if so should I create a message receiver, or is there other options ???)

Upvotes: 1

Views: 272

Answers (3)

daryal
daryal

Reputation: 14929

you may use EventAggregator implementation of Prism framework. 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.

Upvotes: 0

Memoizer
Memoizer

Reputation: 2289

You can create a WindowService (it call a window directly), and inject it into the view model.

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);
                                      }));
        }
    }
}

Upvotes: 3

fhnaseer
fhnaseer

Reputation: 7277

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.
}

Upvotes: 0

Related Questions