继电器命令没有被触发

时间:2015-02-24 17:27:41

标签: c# wpf xaml

我有继电器命令

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


        }
    }

1 个答案:

答案 0 :(得分: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>