2012-10-28 25 views
14

Ho un semplice pulsante che utilizza un comando quando viene eseguito, tutto funziona correttamente ma vorrei passare un parametro di testo quando si fa clic sul pulsante.Passare un parametro a ICommand

Penso che il mio XAML è ok, ma io sono sicuro come modificare la mia classe RelayCommand per ricevere un parametro:

<Button x:Name="AddCommand" Content="Add" 
    Command="{Binding AddPhoneCommand}" 
    CommandParameter="{Binding Text, ElementName=txtAddPhone}" /> 
public class RelayCommand : ICommand 
{ 
    private readonly Action _handler; 
    private bool _isEnabled; 

    public RelayCommand(Action handler) 
    { 
     _handler = handler; 
    } 

    public bool IsEnabled 
    { 
     get { return _isEnabled; } 
     set 
     { 
      if (value != _isEnabled) 
      { 
       _isEnabled = value; 
       if (CanExecuteChanged != null) 
       { 
        CanExecuteChanged(this, EventArgs.Empty); 
       } 
      } 
     } 
    } 

    public bool CanExecute(object parameter) 
    { 
     return IsEnabled; 
    } 

    public event EventHandler CanExecuteChanged; 

    public void Execute(object parameter) 
    { 
     _handler(); 
    } 
} 

risposta

8

Change Action a Action<T> in modo che ci vuole un parametro (probabilmente solo Action<object> è più semplice).

private readonly Action<object> _handler; 

E poi semplicemente passarlo il parametro:

public void Execute(object parameter) 
{ 
    _handler(parameter); 
} 
+0

Grazie che funziona alla grande! Non sono nuovo di WPF, ma sono nuovo di MVVM, quindi i comandi sono un nuovo concetto; ma posso già vedere come potrebbero aiutare i test unitari. Quindi aggiungere non sta dicendo Azione di tipo oggetto ma piuttosto questo delegato accetta un parametro oggetto? –

+0

@MichaelHarper sì, esattamente un delegato che accetta un parametro oggetto. Puoi vedere che hanno definito più tipi di azione lungo queste linee: http://msdn.microsoft.com/en-us/library/018hxwa8.aspx – McGarnagle

+0

Grazie ancora, è stato di grande aiuto: D –

1

si può semplicemente fare questo (nessun cambiamento per RelayCommand o ICommand richiesto):

private RelayCommand _addPhoneCommand; 
public RelayCommand AddPhoneCommand 
{ 
    get 
    { 
     if (_addPhoneCommand == null) 
     { 
      _addPhoneCommand = new RelayCommand(
       (parameter) => AddPhone(parameter), 
       (parameter) => IsValidPhone(parameter) 
      ); 
     } 
     return _addPhoneCommand; 
    } 
} 

public void AddPhone(object parameter) 
{ 
    var text = (string)parameter; 
    ... 
} 

public void IsValidPhone(object parameter) 
    var text = (string)parameter; 
    ... 
} 
0

Si può solo fare

public ICommand AddPhoneCommand 
{ 
    get 
    { 
     return new Command<string>((x) => 
     { 
      if(x != null) { AddPhone(x); } 
     }; 
    } 
} 

Quindi, di cour Se hai il tuo AddPhone:

public void AddPhone(string x) 
{ 
    //handle x 
} 
Problemi correlati