2012-02-06 185 views
2

我試圖傳遞一個命令參數與我的命令。我有一般的命令工作,但傳遞一個參數對我來說似乎不會很好。傳遞命令參數

我想從我的XAML中的分層數據傳遞用戶名屬性。我在這裏做錯了什麼。

我收到和錯誤嘗試用下面的命令語句來編譯:

無法從 'lambda表達式' 到 'System.Action'

<HierarchicalDataTemplate 
    DataType="{x:Type viewModel:UsersViewModel}" 
    ItemsSource="{Binding Children}"> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="{Binding UserName}"> 
      <TextBlock.ContextMenu> 
        <ContextMenu> 
         <MenuItem Header="Edit" Command="{Binding EditCommand}" CommandParameter="{Binding UserName}"/> 
         <MenuItem Header="Delete"/> 
        </ContextMenu> 
       </TextBlock.ContextMenu> 
     </TextBlock> 
    </StackPanel> 
</HierarchicalDataTemplate> 
private RelayCommand _editCommand; 
    public ICommand EditCommand 
    { 
     get 
     { 
      if (_editCommand== null) 
      { 
       _editCommand= new RelayCommand(param => this.LoadUser(object parameter)); 
      } 
      return _editCommand; 
     } 
    } 

    public void LoadUser(object username) 
    { 

    } 

RelayCommand類轉換

public class RelayCommand : ICommand 
{ 
    #region Fields 

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

    #endregion // Fields 

    #region Constructors 

    public RelayCommand(Action<object> execute) 
     : this(execute, null) 
    { 
    } 

    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 parameter) 
    { 
     return _canExecute == null ? true : _canExecute(parameter); 
    } 

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

    public void Execute(object parameter) 
    { 
     _execute(parameter); 
    } 
    #endregion 
} 

感謝您的幫助!

回答

3
new RelayCommand(param => this.LoadUser(object parameter)); 

不應該是這樣:

new RelayCommand(param => this.LoadUser(param)); 
+0

我明白了,我需要在拉姆達的 – rreeves 2012-02-06 22:58:11

+1

@BatMasterson讀了起來:有ISN對於那些簡單的表達,'行動'只是無效的方法,右側是方法體,你可以在其中執行任何你想做的事情。 ['Funcs'](http://msdn.microsoft.com/en-us/library/bb534960.aspx)將是具有返回值的方法。 – 2012-02-06 23:06:46

3

您不應該調用該方法,您應該將其作爲參數傳遞。只需更換new RelayCommand(param => this.LoadUser(object parameter));new RelayCommand(this.LoadUser);

類似的問題在這裏: RelayCommand lambda syntax problem