【问题标题】:Prism Command Binding using Parameter?Prism 命令绑定使用参数?
【发布时间】:2015-05-08 13:11:19
【问题描述】:

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

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>

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

【问题讨论】:

    标签: c# wpf command parameter-passing prism


    【解决方案1】:

    这是一个对我有用的完整解决方案:

    1. 使用 CommandParameter(根据 Dmitry - Spasiba!)

      <TextBlock>
          <Hyperlink CommandParameter="{Binding PersonSelected.PersonKnown2ID}"
                     Command="{Binding NavHomeViewCommand}" >
              <Run Text="{Binding PersonSelected.PersonKnownName2}" />
          </Hyperlink>
      </TextBlock>
      
    2. 更改 DelegateCommand 以使用对象参数

      navHomeViewCommand = new DelegateCommand<object>(NavHomeView);
      
    3. 命令属性保持不变,但方法改为使用参数:

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

    【讨论】:

    • 警告,不要在你的可以执行调用中使用空检查,因为命令总是用空参数初始化,然后设置命令参数但不会刷新命令的 CanExecute 绑定,
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-03-12
      • 2012-10-31
      • 1970-01-01
      • 2019-02-13
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多