How to access command parameter passed to function when using Fody Commander

359 views Asked by At

I am trying to using Fody Commander to implement Sign in command.

My login button XAML is like this:

<Button x:Name="button"
                IsDefault="True"
                Command="{Binding SignInCommand}"
                Style="{DynamicResource AccentedSquareButtonStyle}"
                Grid.Column="1"  Grid.Row="0" Grid.RowSpan="2" Margin="10">
            <Button.CommandParameter>
                <MultiBinding Converter="{StaticResource SignInConverter}">
                    <Binding Path="Text" ElementName="UserName" />
                    <Binding ElementName="Password" />
                </MultiBinding>
            </Button.CommandParameter>
            <TextBlock FontSize="{DynamicResource NormalFontSize}">Sign In</TextBlock>
        </Button>

In my ViewModel I have this:

[OnCommand("SignInCommand")]
    public void OnSignIn()
    {
        //Need to access the parameters passed from the XAML.
    }

I am at loss how to access the parameters I passed from the XAML to the OnSignIn().

2

There are 2 answers

0
Olaru Mircea On

How about adding a parameter for the OnSignIn method in the ViewModel and send it to the class that implements ICommand? In your case SignInCommand.

public class SignInCommand<T> : ICommand
{
    public Action<T> _TargetExecuteMethod;
    public Func<T, bool> _TargetCanExecuteMethod;

    public SignInCommand(Action<T> executeMethod)
    {
        _TargetExecuteMethod = executeMethod;
    }

    public bool CanExecute(object parameter)
    {
        if (_TargetExecuteMethod != null)
            return true;
        return false;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        T tParam = (T)parameter;
        if (_TargetExecuteMethod != null)
            _TargetExecuteMethod(tParam);
    }
}

And in you ViewModel's constructor, you initialize it like this:

signInCommand = new SignInCommand<object>(OnSignIn);

And now, your OnSignInMethod will receive the parameter you want. Further more, you can support the CanExecuted Func too. It's already present in the SignInCommand, just set a new parameter in the constructor, define it in the ViewModel and send it at instantiation.

I gave a pretty straightforward solution here, i am sorry i am not sure what Fody is and unfortunately i don't have the time to check it now. Good luck!

0
NotAgain On

In the end it was ridiculously easy to pass parameter to FODY Commander based commands. I have written a small blog on it.Link - http://ikeptwalking.com/fody-commander-and-wpf-commands/