Reputation: 2986
I am a little lost in how to use the CommandParameter in XAML. I am trying to bind a TextBox and a Button.
This my XAML code:
<TextBox x:Name="txtCity" Height="70"
VerticalAlignment="Top"/>
<Button x:Name="btnCity"
Content="Get"
Background="CornflowerBlue"
Height="70"
Command="{Binding GetweatherCommand}"
CommandParameter="{Binding ElementName=txtCity, Path=Text}"/>
In my ViewModel class I have the following to handle the clic action:
ActionCommand getWeatherCommand; //ActionCommand derivides from ICommand
public ActionCommand GetWeatherCommand
{
get
{
if (getClimaCommand != null)
{
getClimaCommand = new ActionCommand(() =>
{
serviceModel.getClima("????");
});
}
return getWeatherCommand;
}
}
My ActionCommand class:
public class ActionCommand : ICommand
{
Action action;
public ActionCommand(Action action)
{
this.action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
action();
}
}
When I debug, the parameters in the Execute
and CanExecute
methods have the proper value. However, I guess the problem is in the method from the ViewClass (GetWeatherCommand)
. I can't figure out how to pass the parameter.
So, based on the above, does anyone know how can I pass the parameter to the method that will be executed?
Upvotes: 1
Views: 6735
Reputation: 84724
ActionCommand.Execute
is ignoring the command parameter. Try this:
public class ActionCommand<TParam> : ICommand
{
Action<TParam> action;
public ActionCommand(Action<TParam> action)
{
this.action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
action((TParam)parameter);
}
}
And then:
getClimaCommand = new ActionCommand<string>(param =>
{
serviceModel.getClima(param);
});
Upvotes: 3