繁体   English   中英

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

[英]How to create bindable command for custom component in Xamarin.Forms?

我有一个自定义组件,我有一个按钮,我正在尝试创建一个可绑定的命令,以便我可以根据 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);
    }
}

您需要为可绑定属性实现propertychanged以启用绑定。

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;
}

您需要使用TapGestureRecognizer来触发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);
        }
    }
}

在这里上传了一个示例项目,请随时问我任何问题。

 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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM