我有我的继电器命令继电器命令不被解雇
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();
}
}
你可能要设置的'DataContext'到'ViewModel'而不是'MainWindow'本身。 – Bolu 2015-02-24 17:32:23
您需要在ViewModel类中实现INotifyPropertyChanged,以便UI知道何时设置了SearchCommand。 – 2015-02-24 17:34:37