单按钮事件的ICommand

时间:2013-07-26 02:36:08

标签: wpf c#-4.0 mvvm .net-4.0

下面的代码是我的WPF应用程序的MVVM类。在我的MainWindow.xaml.cs文件,MainWindow()构造函数中,我这样做了。

oneWayAuth = new OneWayAuthentication();
DataContext = oneWayAuth

我的主窗口包含多个按钮,我需要通过使用ICommand,

这样的绑定来分配事件

MainWindow.xaml

<Grid>
<Button> Command="{Binding ClickCommand}" Content="Button" Grid.Row="1" Name="button1" />
</Grid>

按钮的内部事件,我应该能够访问oneWayAuth.RandomNumber属性,以便我可以更改它。

我尝试使用以下方法。但我无法通过返回类型传递Action委托。

OneWayAuthentication.cs

public class OneWayAuthentication : INotifyPropertyChanged
{
    private string certData;
    private string isVerifiedCert;
    private string randomNumber;
    private string response;
    private string isVerifiedRes;
    private string resultAuth;

    public string RandomNumber
    {
        get
        {
            return randomNumber;
        }
        set
        {
            randomNumber = value;
            NotifyPropertyChanged("RandomNumber");
        }
    }

    public ICommand ClickCommand
    {
        get
        {
            ICommand intfaceCmnd = new CommandHandler(() => Execute(), () => Switch());
            return intfaceCmnd;
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    #region Private Helpers

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

    #endregion

    public bool Switch()
    {
        return true;
    }

    public void Execute()
    {
        this.RandomNumber = "this is random number";
    }
}

CommandHandler.cs

public delegate bool delCanExecute(object parameter); 
public class CommandHandler:ICommand
{
    private Action _action;
    private Action _canExecute;
    public CommandHandler(Action action1, Action action2)
    {
        _action = action1;
        _canExecute = action2;
    }

    public bool CanExecute(object parameter)
    {
        bool res = _canExecute();
        return res;
    }

    public void Execute(object parameter)
    {
        _action();
    }
    public event EventHandler CanExecuteChanged;
}

2 个答案:

答案 0 :(得分:2)

来自MVVM light的典型命令处理程序(RelayCommand)

class RelayCommand : ICommand
        {
                readonly Action<object> _execute;
                readonly Predicate<object> _canExecute;

                /// <summary>
                /// Initializes a new instance of the <see cref="RelayCommand"/> class.
                /// </summary>
                /// <param name="execute">The method to be called when the command is 
                /// invoked.</param>
                public RelayCommand(Action<object> execute)
                        : this(execute, null)
                { }

                /// <summary>
                /// Initializes a new instance of the <see cref="RelayCommand"/> class.
                /// </summary>
                /// <param name="execute">The method to be called when the command is 
                /// invoked.</param>
                /// <param name="canExecute">the method that determines whether the command 
                /// can execute in its current state.</param>
                public RelayCommand(Action<object> execute, Predicate<object> canExecute)
                {
                        if (execute == null)
                                throw new ArgumentNullException("execute");

                        _execute = execute;
                        _canExecute = canExecute;
                }

                /// <summary>
                /// Defines the method that determines whether the command can execute in 
                /// its current state.
                /// </summary>
                /// <param name="parameter">Data used by the command.  If the command does 
                /// not require data to be passed, this object can be set to null.</param>
                /// <returns>
                /// true if this command can be executed; otherwise, false.
                /// </returns>
                [DebuggerStepThrough]
                public bool CanExecute(object parameter)
                {
                        return _canExecute == null ? true : _canExecute(parameter);
                }

                /// <summary>
                /// Occurs when changes occur that affect whether or not the command should 
                /// execute.
                /// </summary>
                public event EventHandler CanExecuteChanged
                {
                        add { CommandManager.RequerySuggested += value; }
                        remove { CommandManager.RequerySuggested -= value; }
                }

                /// <summary>
                /// Defines the method to be called when the command is invoked.
                /// </summary>
                /// <param name="parameter">Data used by the command.  If the command does 
                /// not require data to be passed, this object can be set to null.</param>
                public void Execute(object parameter)
                {
                        _execute(parameter);
                }
        }

使用对象的操作意味着您可以将参数传递给您的命令,并为Predicate传递参数,但它返回bool。

答案 1 :(得分:1)

Instead Of Action use Func<bool>

public class CommandHandler:ICommand
{
private Action _action;
private Func<bool>_canExecute;
public CommandHandler(Action action1, Func<bool>action2)
{
    _action = action1;
    _canExecute = action2;
}

<强>更新

 public ICommand ClickCommand
{
    get
    {
        ICommand intfaceCmnd = new CommandHandler(() => Execute(), () => Switch());
        return intfaceCmnd;
    }
}