我有我的中继命令
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/