2015-02-24 44 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