Один из способов решить эту проблему - использовать шаблон MVVM и RelayCommand
класс из учебник .
RelayCommand.cs
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool> _canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
public void Execute(object parameter) => _execute(parameter);
}
Затем вы должны установить DataContext
вашего окна (или UserControl), оно требуется для разрешения привязок в xaml.
Один из способов сделать это:
MainWindow.xaml
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
Настройка Text
Свойство и KeyPressedCommand
из примера "что-то вроде этого" в классе MainViewModel
.
MainViewModel.cs
public class MainViewModel : INotifyPropertyChanged
{
private bool _text;
public bool Text
{
get => _text;
set
{
_text = value;
OnPropertyChanged(nameof(Text));
// Text changed!
}
}
public ICommand KeyPressedCommand => new RelayCommand(obj =>
{
if (obj is Key key) {
// do something here with the 'key' provided by CommandParameter
}
});
public MainViewModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}