2015-02-24 43 views
2

我有我的繼電器命令繼電器命令不被解僱

public class RelayCommand : ICommand 
{ 

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

    private Action methodToExecute; 

    private Func<bool> canExecuteEvaluator; 

    public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator) 
    { 
     this.methodToExecute = methodToExecute; 
     this.canExecuteEvaluator = canExecuteEvaluator; 
    } 
    public RelayCommand(Action methodToExecute) 
     : this(methodToExecute, null) 
    { 
    } 

     public bool CanExecute(object parameter) 
    { 
     if (this.canExecuteEvaluator == null) 
     { 
      return true; 
     } 
     else 
     { 
      bool result = this.canExecuteEvaluator.Invoke(); 
      return result; 
     } 
    } 

    public void Execute(object parameter) 
    { 
     this.methodToExecute.Invoke(); 
    } 
} 

我的視圖模型

public class ViewModel 
{ 

    public ICommand SearchCommand { get; set; } 


    public ViewModel() 
    { 
     SearchCommand = new RelayCommand(ProcessFile); 
    } 
    void ProcessFile() 
    { 
    } 
//Some code 
} 

我的.xaml

<Button Width="70" Margin="5" Content="Search" Command="{Binding Path= ViewModel.SearchCommand}" ></Button> 

我有還設置數據上下文開始

DataContext="{Binding RelativeSource={RelativeSource Self}}"

我身後

public partial class MainWindow : Window 
    { 
     public ViewModel ViewModel { get; set; } 

     public MainWindow() 
     { 
      InitializeComponent(); 
      ViewModel = new ViewModel(); 


     } 
    } 
+0

你可能要設置的'DataContext'到'ViewModel'而不是'MainWindow'本身。 – Bolu 2015-02-24 17:32:23

+0

您需要在ViewModel類中實現INotifyPropertyChanged,以便UI知道何時設置了SearchCommand。 – 2015-02-24 17:34:37

回答

1

代碼在XAML中刪除DataContext設置和更改您的構造函數

public MainWindow() 
{ 
    InitializeComponent(); 
    ViewModel = new ViewModel(); 
    DataContext = ViewModel; 
} 

你的XAML是有約束力的數據上下文切換到窗口,而不是您正在創建的視圖模型實例。

您還需要將路徑更改爲您的綁定是相對的DataContext(也就是現在你的視圖模型)

<Button Width="70" Margin="5" Content="Search" Command="{Binding Path=SearchCommand}" ></Button> 

<TextBox Width="300" Margin="5" Text="{Binding Path=SearchTextBox}"> </TextBox> 
+0

嗨史蒂夫,我有改變constructor.but命令沒有被解僱。我已經添加屬性在我的viewmodel公共字符串SerachTextBox {get;組; }並在其構造函數中初始化爲「abc」。現在,我已將文本框綁定到文本框中,但數據不會顯示正常。 – 2015-02-24 17:42:52

+0

嗨史蒂夫,我發現soultion我已經改變我的binding.it鍵入錯誤.removed ViewModel,現在它的工作正常。 。感謝您的解決方案 – 2015-02-24 17:50:33

+0

已修改的答案包括對應該進行的綁定的更改。 – 2015-02-24 17:51:15