Reputation: 2266
I have followed several tutorials on consuming native views in Xamarin.Forms, But I didn't succeed in Binding Command to From ViewModel to the Native View.
Here is the code for the custom Native control in android:
public class MyFAB : FloatingActionButton
{
public Command Command { get; set; }
public MyFAB (Context context) : base(context)
{
this.SetImageResource(Resource.Drawable.ic_add_white_24dp);
Click += (sender, e) =>
{
Command?.Execute(null);
};
}
}
Here is the Xaml Code:
<droidCustom:AddFAB x:Arguments="{x:Static formsDroid:Forms.Context}" UseCompatPadding="true" Command="{Binding AddCategoryCommand}"
AbsoluteLayout.LayoutBounds="1,1,AutoSize,AutoSize" AbsoluteLayout.LayoutFlags="PositionProportional"/>
The View is shown properly, but the command is not fired, and when I debug, the Command is never assigned it is always null. When I go through blog posts online, they say the command binding will not need any bindable property... but here I still get issues.
Upvotes: 1
Views: 711
Reputation: 5313
You've created a simple Command
property. To achieve this, you must create a BindableProperty
instead.
Change the Command
's property declaration to this and it should work:
public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(MyFAB), null);
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Adding support to command parameters
public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create(nameof(CommandParameter), typeof(object), typeof(MyFAB), null);
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
And the Click
handler:
Click += (sender, e) =>
{
Command?.Execute(CommandParameter);
};
I hope it helps you. Take a look at the official Microsoft docs about BindablePropperties
to more detailed explanation
Upvotes: 1