【问题标题】:Binding Command to Native Views in Xamarin.forms Xaml在 Xamarin.forms Xaml 中将命令绑定到本机视图
【发布时间】:2018-09-14 03:15:37
【问题描述】:

我已经关注了几个关于在 Xamarin.Forms 中使用本机视图的教程,但是我没有成功将命令绑定到从 ViewModel 到本机视图。

下面是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"/>

视图正确显示,但命令未触发,当我调试时,命令从未分配,它始终为空。 当我在线浏览博客文章时,他们说命令绑定不需要任何可绑定属性......但在这里我仍然遇到问题。

【问题讨论】:

    标签: c# xaml xamarin binding xamarin.forms


    【解决方案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更详细的解释

    【讨论】:

    • 感谢您的帮助,但没有成功,GetValue 和 SetValue 方法无法识别,因为 Command 位于从 Floating 操作按钮继承的类中,并且不是 BindableObject。根据文档,只有 BIndableObjects 有 Get 和 SetValue
    • 你是绝对正确的。我已经错过了。我会想办法让它发挥作用。在此之前,您将无法使用绑定。
    • 如果我们将MyFAB 继承从FloatingActionButton 更改为View,公开您需要的属性、事件和方法,然后将FloatingActionButton 的实例设置为您自定义的NativeControl看法?你觉得它适合你吗?
    • 如果我在共享项目上它会工作,但实际上我在Android端,试图创建一个FAB,并在共享项目中绑定命令。视图显示,但命令是问题,在线他们说不需要 Bindable 属性,但我可以绑定命令。
    • 创建一个FAB,并在共享项目中绑定命令
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2022-01-09
    相关资源
    最近更新 更多