Search code examples
c#wpfxamlprismcommandbinding

Multiple parameters with Command binding


I have a textblock with command binding and using Prism library.

this is the XAML parth:

<TextBlock Margin="0,10,0,0">SocialSecurityNumer:</TextBlock>
<TextBox Name="SSNText" GotFocus="TextBox_GotFocus" Text="{Binding SSN, UpdateSourceTrigger=PropertyChanged}" Margin="0,3,0,0"/>

And this is the ViewModel behind:

public FindViewModel()
{
    var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();

    FindCommand = new DelegateCommand(
        () => eventAggregator.GetEvent<SSNChangedEvent>().Publish(SSN),
        () => !string.IsNullOrWhiteSpace(Kennitala)
        );
}

public DelegateCommand FindCommand { get; set; }

private string ssn;
public string SSN
{
    get { return ssn; }
    set
    {
        if (ssn== value)
            return;

        ssn = value;
        RaisePropertyChanged(() => SSN);
        FindCommand.RaiseCanExecuteChanged();
    }
}

And this is the GridViewModel that listen for this event trigger and fire up a function with SSN as a parameter

public class GridViewModel : NotificationObject
{
    public GridViewModel()
    {
        var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
        eventAggregator.GetEvent<SSNChangedEvent>().Subscribe(GetData);
    }

    public ObservableCollection<Investment> Investments { get; set; }

    private void GetData(string ssn)
    {
        var list = GeniusConnection.GetDataFromWebService(ssn);

        Investments = new ObservableCollection<Investment>(list);

        RaisePropertyChanged(() => Investment);
    }
}

How can i add another parameter, for example datetime parameter, the part that confuses me is:

FindCommand = new DelegateCommand(
            () => eventAggregator.GetEvent<SSNChangedEvent>().Publish(SSN),
            () => !string.IsNullOrWhiteSpace(Kennitala)
            );

This Publish function takes just one parameter and therefor i don´t see how i can easily add multiple paramters.??


Solution

  • you should create a class that holds all neccessary parameters that you want to publish.

     public class SSNChangedEventParams
     {
         public string SSN{get;set;}
         public DateTime Dt{get;set;}
         ...
     }
    

    and then Publish an instance of this class:

     eventAggregator.GetEvent<SSNChangedEvent>().Publish(new SSNChangedEventParams(){SSN=SSN, Dt = DateTime.Now})