使用参数进行Prism命令绑定?

时间:2015-03-06 20:29:17

标签: c# wpf command parameter-passing prism

我有一个工作超链接如下:

XAML:

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

构造

 navHomeViewCommand = new DelegateCommand(NavHomeView);

命令:

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

如果我想要多个超链接,例如......

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

我是否必须为每个命令创建一个新命令,或者是否有办法为现有NavHomeView命令的每个超链接传递一个不同的参数(int),以便我可以重用此命令?

2 个答案:

答案 0 :(得分:7)

这是一个适合我的完整解决方案:

  1. 使用CommandParameter(根据Dmitry - Spasiba!)
  2. <TextBlock>
        <Hyperlink CommandParameter="{Binding PersonSelected.PersonKnown2ID}"
           Command="{Binding NavHomeViewCommand}" >
           <Run Text="{Binding PersonSelected.PersonKnownName2}" />
        </Hyperlink>
    </TextBlock>
    
    1. 将DelegateCommand更改为使用对象参数
    2. navHomeViewCommand = new DelegateCommand<object>(NavHomeView);
      
      1. 命令属性保持不变,但方法已更改为使用参数:
      2. 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);
        }
        

答案 1 :(得分:2)

您可以使用超链接的'CommandParameter'属性。

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