c# - 中继命令没有被触发

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

我的 View 模型

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


        }
    }

最佳答案

删除 XAML 中的 DataContext 设置并将您的构造函数更改为

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

您的 XAML 将数据上下文绑定(bind)到窗口,而不是您正在创建的 View 模型实例。

您还需要将绑定(bind)的路径更改为相对于 DataContext(现在是您的 View 模型)

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

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

关于c# - 中继命令没有被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28702342/

相关文章:

c# - 如何在 Entity Framework 中的 DbSet 属性上设置过滤选项?

c# - 如何禁用 WPF ListBox 中的水平滚动?

c# - WPF - ListView 中的 TextBlock 未水平对齐

c# - WPF/Xaml - 获取动态元素的高度

c# - 在 C# 中将 .EPS 转换为图像

c# - 在部分 View 中呈现的模型属性值不正确

c# - 使用 RSACryptoServiceProvider 加密数据在我看来是一个奇怪的功能

WPF - Task.Run(() => window.ShowDialog) 失败

wpf - 如果元素不支持命令,是否有任何通用程序在 MVVM 中实现命令?

c# - 我将代码写入哪个文件?有很多 .xaml.cs 文件