'How to create bindable command for custom component in Xamarin.Forms?
I've a custom component where I've button and I'm trying to create a bindable command so that I can perform action based on viewmodel. I've tried few things but nothing seems to be working :
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(MySample), null);
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Helper method for invoking commands safely
public static void Execute(ICommand command)
{
if (command == null) return;
if (command.CanExecute(null))
{
command.Execute(null);
}
}
Solution 1:[1]
You need to implement propertychanged
for bindable property to enable binding.
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(nameof(Command), typeof(Xamarin.Forms.Command), typeof(MySample), null, propertychanged: OnCommandPropertyChanged);
stativ void OnCommandPropertyChanged (BindableObject bindable, object oldValue, object newValue)
{
(bindable as MySample).Command = (Command)newValue;
}
Solution 2:[2]
You need to use TapGestureRecognizer
to trigger Command
:
public partial class View1 : ContentView
{
public View1()
{
InitializeComponent();
var gestureRecognizer = new TapGestureRecognizer();
gestureRecognizer.Tapped += (s, e) => {
if (Command != null && Command.CanExecute(null))
{
Command.Execute(null);
}
};
this.GestureRecognizers.Add(gestureRecognizer);
}
// BindableProperty implementation
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(View1), null);
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Helper method for invoking commands safely
public static void Execute(ICommand command)
{
if (command == null) return;
if (command.CanExecute(null))
{
command.Execute(null);
}
}
}
I uploaded a sample project here and feel free to ask me any question.
Solution 3:[3]
public ICommand MyCommand
{
get => (ICommand)GetValue(MyCommandProperty);
set => SetValue(MyCommandProperty, value);
}
public static BindableProperty MyCommandProperty = BindableProperty.Create(
propertyName: "Command",
returnType: typeof(ICommand),
declaringType: typeof(View1),
defaultValue: null,
defaultBindingMode: BindingMode.TwoWay,
propertyChanged: MyCommandPropertyChanged);
public static void MyCommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (CustomSignInTemplate)bindable;
control.tempbtn.Command = (ICommand)newValue;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | nevermore |
Solution 3 | Dhruv |