Ches Scehce
Ches Scehce

Reputation: 265

Prism Command Binding using Parameter?

I have a working hyperlink as follow:

XAML:

 <TextBlock >
    <Hyperlink Command="{Binding NavHomeViewCommand}" >
       <Run Text="{Binding PersonSelected.PersonKnownName}" />
    </Hyperlink>
</TextBlock>

Constructor:

 navHomeViewCommand = new DelegateCommand(NavHomeView);

Command:

     private readonly ICommand navHomeViewCommand;
    public ICommand NavHomeViewCommand
    {
        get
        { return navHomeViewCommand; }
    }
    private void NavHomeView()
    {
        int val;
        val = PersonSelected.PersonKnownID);
        var parameters = new NavigationParameters();
        parameters.Add("To", val);
        _regionManager.RequestNavigate("MainRegion", new Uri("HomeView", UriKind.Relative), parameters);
    }

If I want to have multiple hyperlinks such as...

     <Hyperlink Command="{Binding NavHomeViewCommand}" >
       <Run Text="{Binding PersonSelected.PersonKnownName}" />
    </Hyperlink>
    <Hyperlink Command="{Binding NavHomeViewCommand}" >
       <Run Text="{Binding PersonSelected.PersonKnownName2}" />
    </Hyperlink>
    <Hyperlink Command="{Binding NavHomeViewCommand}" >
       <Run Text="{Binding PersonSelected.PersonKnownName3}" />
    </Hyperlink>

Do I have to make a new Command for each or is there a way to pass a different parameter (int) for each hyperlink to the existing NavHomeView command so I can reuse this command?

Upvotes: 7

Views: 17043

Answers (2)

Ches Scehce
Ches Scehce

Reputation: 265

Here is a complete solution that worked for me:

  1. Use CommandParameter (as per Dmitry - Spasiba!)

    <TextBlock>
        <Hyperlink CommandParameter="{Binding PersonSelected.PersonKnown2ID}"
                   Command="{Binding NavHomeViewCommand}" >
            <Run Text="{Binding PersonSelected.PersonKnownName2}" />
        </Hyperlink>
    </TextBlock>
    
  2. Change DelegateCommand to use object parameter

    navHomeViewCommand = new DelegateCommand<object>(NavHomeView);
    
  3. Command Properties remain unchanged but method changed to use parameter:

    private readonly ICommand navHomeViewCommand;
    public ICommand NavHomeViewCommand
    {
        get { return navHomeViewCommand; }
    }
    
    private void NavHomeView(object ID)
    {
        int val = Convert.ToInt32(ID);
        var parameters = new NavigationParameters();
        parameters.Add("To", val);
       _regionManager.RequestNavigate("MainRegion", new Uri("HomeView", UriKind.Relative), parameters);
    }
    

Upvotes: 10

martavoi
martavoi

Reputation: 7092

You can use 'CommandParameter' property of the Hyperlink.

 <Hyperlink Command="{Binding NavHomeViewCommand}" CommandParameter="1" >
       <Run Text="{Binding PersonSelected.PersonKnownName}" />
 </Hyperlink>

Upvotes: 2

Related Questions