2012-10-28 7 views
14

पर पैरामीटर पास करना मेरे पास एक साधारण बटन है जो निष्पादित होने पर कमांड का उपयोग करता है, यह सब ठीक काम कर रहा है लेकिन बटन क्लिक होने पर मैं टेक्स्ट पैरामीटर पास करना चाहता हूं। बसआईसीओएमएंड

<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(); 
    } 
} 

उत्तर

8

बदलें Action<T> इतना है कि यह एक पैरामीटर लेता करने के लिए Action (शायद:

मुझे लगता है कि मेरी XAML ठीक है, लेकिन मैं कैसे मेरे RelayCommand वर्ग संपादित करने के लिए एक पैरामीटर प्राप्त करने के लिए अनिश्चित हूँ Action<object> सबसे आसान है)।

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

धन्यवाद जो बहुत अच्छा काम करता है! मैं WPF के लिए नया नहीं हूं लेकिन मैं एमवीवीएम में नया हूं इसलिए आदेश एक नई अवधारणा है; लेकिन मैं पहले से ही देख सकता हूं कि वे यूनिट परीक्षणों में कैसे मदद करेंगे। तो जोड़ना ऑब्जेक्ट की क्रिया नहीं कह रहा है बल्कि यह प्रतिनिधि एक ऑब्जेक्ट पैरामीटर लेता है? –

+0

@ माइकल हार्पर हां, बिल्कुल, एक प्रतिनिधि जो एक ऑब्जेक्ट पैरामीटर लेता है। आप देख सकते हैं कि उन्होंने उन पंक्तियों के साथ कई क्रिया प्रकारों को परिभाषित किया है: http://msdn.microsoft.com/en-us/library/018hxwa8.aspx – McGarnagle

+0

धन्यवाद, एक बड़ी मदद मिली: डी –

1

आप आसानी से इस (कोई आवश्यक RelayCommand या ICommand को बदलना) कर सकते हैं::

private readonly Action<object> _handler; 

और फिर बस इसे पैरामीटर पारित

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

तुम बस

कर सकता है
public ICommand AddPhoneCommand 
{ 
    get 
    { 
     return new Command<string>((x) => 
     { 
      if(x != null) { AddPhone(x); } 
     }; 
    } 
} 

फिर, cour से आपके AddPhone:

public void AddPhone(string x) 
{ 
    //handle x 
} 
संबंधित मुद्दे