Reputation: 661
I want to pass serval parameters to a command via commandparameter in xaml.
<i:InvokeCommandAction Command="{Binding HideLineCommand, ElementName=militaryLineAction}"
CommandParameter="{Binding ID, ElementName=linesSelector}"/>
In above sample, I want to pass others variables to the command beside the ID variable. How can I achieve it? Great thanks.
Upvotes: 4
Views: 16326
Reputation: 19296
You can use MultiBinding with a converter.
Check this example.
Let's suppose that you have Person class.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
And you want this class as your command parameter.
Your XAML should look like this:
<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>
Where SourceData
is a Person object.
And myPersonConverter
is a PersonConverter object.
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();
}
}
And in your command you can use Person object as parameter:
public ICommand SendStatus { get; private set; }
private void OnSendStatus(object param)
{
Person p = param as Person;
if (p != null)
{
}
}
Upvotes: 7