2009-10-14 29 views
14

Tôi ràng buộc lệnh của tôi như:Nhận CommandParameter giá trị trong MVVM

<Button Command="{Binding NextCommand}" 
    CommandParameter="Hello" 
    Content="Next" /> 

Ở đây, tôi cũng ràng buộc tài sản CommandParameter của nó, bây giờ làm thế nào để lấy giá trị của nó từ NextCommand.

public ICommand NextCommand 
    { 
     get 
     { 
      if (_nextCommand == null) 
      { 
       _nextCommand = new RelayCommand(
        param => this.DisplayNextPageRecords() 
        //param => true 
        ); 
      } 
      return _nextCommand; 
     } 
    } 

định nghĩa hàm của nó:

public ObservableCollection<PhonesViewModel> DisplayNextPageRecords() 
    { 

      //How to fetch CommandParameter value which is set by 
      //value "Hello" at xaml. I want here "Hello" 
      PageNumber++; 
      CreatePhones(); 
      return this.AllPhones; 

    } 

Làm thế nào để lấy giá trị CommandParameter?

Xin cảm ơn trước.

Trả lời

33

Thay đổi định nghĩa phương pháp của bạn:

public ObservableCollection<PhonesViewModel> DisplayNextPageRecords(object o) 
{ 
    // the method's parameter "o" now contains "Hello" 
    PageNumber++; 
    CreatePhones(); 
    return this.AllPhones; 
} 

Xem như thế nào khi bạn tạo RelayCommand của bạn, nó "Execute" lambda mất một tham số? Chuyển nó vào phương pháp của bạn:

_nextCommand = new RelayCommand(param => this.DisplayNextPageRecords(param)); 
+1

Cảm ơn bạn rất nhiều, công việc của nó rất nhiều. Cảm ơn bạn lần nữa. –

+0

và sau đó bạn có thể sử dụng như '_nextCommand = new RelayCommand (this.DisplayNextPageRecords);' –