2012-11-14 124 views
2

我想通過xaml中的commandparameter將參數傳遞給一個命令。將多參數傳遞給xaml中的CommandParameter

<i:InvokeCommandAction Command="{Binding HideLineCommand, ElementName=militaryLineAction}" 
         CommandParameter="{Binding ID, ElementName=linesSelector}"/> 

在上面的示例中,我想將其他變量傳遞給ID變量旁邊的命令。我怎樣才能實現它?萬分感謝。

+0

你不能做到這一點。 –

+0

這可能有助於查看更多的代碼。是'militaryLineAction'和'linesSelector' UI元素嗎? –

回答

5

您可以使用MultiBinding轉換器

檢查此示例。

讓我們假設你有Person類。

public class Person 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

而且您希望將此類作爲您的命令參數。

你的XAML應該是這樣的:

<Button Content="Start" 
       DataContext="{Binding SourceData}" 
       > 
      <i:Interaction.Triggers> 
       <i:EventTrigger EventName="Click"> 
        <i:InvokeCommandAction Command="{Binding SendStatus, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"> 
         <i:InvokeCommandAction.CommandParameter> 
          <MultiBinding Converter="{StaticResource myPersonConverter}"> 
           <MultiBinding.Bindings> 
            <Binding Path="Name" /> 
            <Binding Path="Age" /> 
           </MultiBinding.Bindings> 
          </MultiBinding> 
         </i:InvokeCommandAction.CommandParameter> 
        </i:InvokeCommandAction> 
       </i:EventTrigger> 
      </i:Interaction.Triggers> 
     </Button> 

SourceData是一個Person對象。

myPersonConverter是一個PersonConverter對象。

public class PersonConverter : IMultiValueConverter 
    { 
     public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      if (values != null && values.Length == 2) 
      { 
       string name = values[0].ToString(); 
       int age = (int)values[1]; 

       return new Person { Name = name, Age = age }; 
      } 
      return null; 
     } 

     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

而在你的命令,你可以使用Person對象作爲參數:

public ICommand SendStatus { get; private set; } 
    private void OnSendStatus(object param) 
    { 
     Person p = param as Person; 
     if (p != null) 
     { 

     } 
    } 
+0

非常感謝!這是一個非常有用的技能。它適用於這種多綁定實現。謝謝。 – user1205398

+0

不客氣:) – kmatyaszek

+0

這真的幫了我。謝謝@kmatyaszek +1 –