C# 如何在Xamarin.Forms中为自定义组件创建可绑定命令?

C# 如何在Xamarin.Forms中为自定义组件创建可绑定命令?,c#,xamarin,xamarin.forms,C#,Xamarin,Xamarin.forms,我有一个自定义组件,其中有一个按钮,我正在尝试创建一个可绑定的命令,以便可以基于viewmodel执行操作。 我尝试了一些方法,但似乎没有任何效果: public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(MySample), null); public ICommand Command {

我有一个自定义组件,其中有一个按钮,我正在尝试创建一个可绑定的命令,以便可以基于viewmodel执行操作。 我尝试了一些方法,但似乎没有任何效果:

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);
    }
}
你需要

公共静态只读BindableProperty CommandProperty=
Create(nameof(Command)、typeof(Xamarin.Forms.Command)、typeof(MySample)、null、propertychanged:OnCommandPropertyChanged);
stativ void OnCommandPropertyChanged(bindable对象bindable、对象oldValue、对象newValue)
{
(可绑定为MySample.Command=(Command)newValue;
}

您需要使用
点击手势识别器
来触发
命令

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);
        }
    }
}
我上传了一个示例项目,可以随时问我任何问题。

public ICommand MyCommand
{
get=>(ICommand)GetValue(MyCommand属性);
set=>SetValue(MyCommandProperty,value);
}
public static BindableProperty MyCommandProperty=BindableProperty.Create(
propertyName:“命令”,
returnType:typeof(ICommand),
declaringType:typeof(视图1),
defaultValue:null,
defaultBindingMode:BindingMode.TwoWay,
属性更改:MyCommand和属性更改);
public static void myCommand属性已更改(BindableObject bindable、object oldValue、object newValue)
{
var控制=(CustomSignInTemplate)可绑定;
control.tempbtn.Command=(ICommand)newValue;

}
现在已尝试使用!!应用propertyChanged event.Great后,在xaml上绑定命令,如:command={Binding NextCommand}。如果这解决了你的问题,请投票并接受。这将帮助其他用户回答同样的问题。嘿!!我也试过同样的方法进入,但不起作用。我还添加了属性更改事件。它更像是在整个视图上创建行为,而不是在特定元素上创建行为。