我已经按照几个关于在Xamarin.Forms中使用本机视图的教程,但是我没有在绑定命令中成功从ViewModel到Native View。
以下是android中自定义Native控件的代码:
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);
};
}
}
这是Xaml代码:
<droidCustom:AddFAB x:Arguments="{x:Static formsDroid:Forms.Context}" UseCompatPadding="true" Command="{Binding AddCategoryCommand}"
AbsoluteLayout.LayoutBounds="1,1,AutoSize,AutoSize" AbsoluteLayout.LayoutFlags="PositionProportional"/>
正确显示视图,但未触发该命令,并且在调试时,从不分配命令,它始终为null。 当我在网上浏览博客文章时,他们说命令绑定不需要任何可绑定的属性......但在这里我仍然遇到问题。
答案 0 :(得分:1)
您已创建了一个简单的Command
属性。为此,您必须改为创建BindableProperty
。
将Command
的属性声明更改为此,它应该有效:
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); }
}
Click
处理程序:
Click += (sender, e) =>
{
Command?.Execute(CommandParameter);
};
我希望它可以帮到你。请查看official Microsoft docs about BindablePropperties
更详细的说明