绑定按钮点击一个方法 [英] Binding Button click to a method

查看:24
本文介绍了绑定按钮点击一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到可观察对象集合的数据网格.我想要做的是有一个按钮,该按钮将执行表示单击的按钮行的对象的方法.所以我现在拥有的是这样的:

I have a datagrid bound to an observable collection of objects. What I want to do is have a button that will execute a method of the object representing the row of the button that was clicked. So what I have now is something like this:

            <DataGridTemplateColumn Header="Command">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Name="cmdCommand" Click="{Binding Command}" 
                                Content="Command"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

哪个不起作用并报告以下错误:

Which doesn't work and reports the following error:

Click="{绑定命令}" 无效.{Binding Command}"不是有效的事件处理程序方法名称.只有生成的或代码隐藏的类上的实例方法才有效.

Click="{Binding Command}" is not valid. '{Binding Command}' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid.

我已经查看了命令绑定,但看起来它最终只会转到单个外部命令,而不是绑定到行的对象.我让它在后面的代码上使用事件处理程序工作,然后将其路由到绑定到所选行的项目(因为单击按钮时该行被选中),但这似乎处理这个问题的方式很糟糕,我假设我'我只是在这里遗漏了一些东西.

I've looked at command binding but that looks like it would just end up going to a single external command instead of to the object bound to the row. I have it working using an event handler on the code behind and then routing it to the item bound to the selected row (since the row gets selected when the button is clicked) but that seems like poor way of handing this and I assume I'm just missing something here.

推荐答案

我一直这样做.下面是一个示例以及您将如何实现它.

I do this all the time. Here's a look at an example and how you would implement it.

更改您的 XAML 以使用按钮的 Command 属性而不是 Click 事件.我使用 SaveCommand 这个名字,因为它比名为 Command 的东西更容易理解.

Change your XAML to use the Command property of the button instead of the Click event. I am using the name SaveCommand since it is easier to follow then something named Command.

<Button Command="{Binding Path=SaveCommand}" />

Button 绑定到的 CustomClass 现在需要有一个名为 SaveCommand 的属性,类型为 ICommand.它需要指向执行命令时要运行的 CustomClass 上的方法.

Your CustomClass that the Button is bound to now needs to have a property called SaveCommand of type ICommand. It needs to point to the method on the CustomClass that you want to run when the command is executed.

public MyCustomClass
{
    private ICommand _saveCommand;

    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new RelayCommand(
                    param => this.SaveObject(), 
                    param => this.CanSave()
                );
            }
            return _saveCommand;
        }
    }

    private bool CanSave()
    {
        // Verify command can be executed here
    }

    private void SaveObject()
    {
        // Save command execution logic
    }
}

上面的代码使用了一个 RelayCommand,它接受两个参数:要执行的方法,以及命令是否可以执行的真/假值.RelayCommand 类是一个单独的 .cs 文件,其代码如下所示.我从乔什史密斯那里得到的 :)

The above code uses a RelayCommand which accepts two parameters: the method to execute, and a true/false value of if the command can execute or not. The RelayCommand class is a separate .cs file with the code shown below. I got it from Josh Smith :)

/// <summary>
/// A command whose sole purpose is to 
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
/// </summary>
public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;        

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;           
    }

    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameters)
    {
        return _canExecute == null ? true : _canExecute(parameters);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameters)
    {
        _execute(parameters);
    }

    #endregion // ICommand Members
}

这篇关于绑定按钮点击一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆