我有我的繼電器命令繼電器命令不被解僱
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