I have a simple button that uses a command when executed, this is all working fine but I would like to pass a text parameter when the button is clicked.
I think my XAML is ok, but I'm unsure how to edit my RelayCommand
class to receive a parameter:
<Button x:Name="AddCommand" Content="Add"
Command="{Binding AddPhoneCommand}"
CommandParameter="{Binding Text, ElementName=txtAddPhone}" />
public class RelayCommand : ICommand
{
private readonly Action _handler;
private bool _isEnabled;
public RelayCommand(Action handler)
{
_handler = handler;
}
public bool IsEnabled
{
get { return _isEnabled; }
set
{
if (value != _isEnabled)
{
_isEnabled = value;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
public bool CanExecute(object parameter)
{
return IsEnabled;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_handler();
}
}
A parameter can be passed through the "CommandParameter" property. Once the button is clicked the selected address value is passed to the ICommand. Execute method. The CommandParameter is sent to both CanExecute and Execute events.
The Command Class Because ICommand is part of Microsoft Windows, it has been used for years with Windows MVVM applications. Using a Windows class that implements ICommand allows you to share your ViewModels between Windows applications and Xamarin. Forms applications. If sharing ViewModels between Windows and Xamarin.
The RelayCommand and RelayCommand<T> are ICommand implementations that can expose a method or delegate to the view. These types act as a way to bind commands between the viewmodel and UI elements.
Change Action
to Action<T>
so that it takes a parameter (probably just Action<object>
is easiest).
private readonly Action<object> _handler;
And then simply pass it the parameter:
public void Execute(object parameter)
{
_handler(parameter);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With