MVVM WPF按钮命令绑定 - RelayCommand

时间:2015-04-02 15:06:38

标签: c# wpf mvvm

很抱歉,如果这是一个愚蠢的问题,但我似乎无法解决,基本上我在窗口上有一个按钮来保存数据。我在这里提到了一类RelayCommand(最佳答案) Binding Button click to a method 每次运行我的项目时,都会触发ICommand SaveCommand方法。从这里创建了一个循环并不断循环。但是,当窗口出现时,按“保存”按钮实际上不会导致命中ICommand SaveCommand方法。我该如何解决这个问题?谢谢大家。

我的观点:

<av:Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="81" Height="44" Margin="52,0,0,20" av:Grid.RowSpan="2" Command ="{Binding SaveCommand}"/>

我的ViewModel:

private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    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

        return true;
    }

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

RelayCommand Class:

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
}

2 个答案:

答案 0 :(得分:3)

你在SaveCommand的{​​{1}}部分犯了一个错误/拼写错误,你应该改变

getif (_saveCommand != null)

答案 1 :(得分:0)

您的CanSave方法返回false。

考虑解决这个问题。