Tư liệu câu trả lời này cho người khác, như có một cách đơn giản hơn nhiều để làm điều này mà hiếm khi được tham chiếu, và không cần chạm vào XAML ở tất cả.
Để liên kết lối tắt bàn phím, trong trình tạo cửa sổ, chỉ cần thêm một KeyBinding mới vào bộ sưu tập InputBindings. Như lệnh, vượt qua trong lớp lệnh tùy ý của bạn thực hiện ICommand. Đối với phương thức thực hiện, chỉ cần thực hiện bất kỳ logic nào bạn cần. Trong ví dụ dưới đây, lớp WindowCommand của tôi nhận một ủy nhiệm rằng nó sẽ thực thi bất cứ khi nào được gọi. Khi tôi xây dựng WindowCommand mới để vượt qua với ràng buộc của tôi, tôi chỉ đơn giản là chỉ ra trong initializer của tôi, phương pháp mà tôi muốn WindowCommand để thực thi.
Bạn có thể sử dụng mẫu này để tìm ra các phím tắt nhanh của riêng bạn.
public YourWindow() //inside any WPF Window constructor
{
...
//add this one statement to bind a new keyboard command shortcut
InputBindings.Add(new KeyBinding(//add a new key-binding, and pass in your command object instance which contains the Execute method which WPF will execute
new WindowCommand(this)
{
ExecuteDelegate = TogglePause //REPLACE TogglePause with your method delegate
}, new KeyGesture(Key.P, ModifierKeys.Control)));
...
}
Tạo một lớp WindowCommand đơn giản, thực hiện ủy quyền thực hiện để kích hoạt bất kỳ phương pháp nào được đặt trên đó.
public class WindowCommand : ICommand
{
private MainWindow _window;
//Set this delegate when you initialize a new object. This is the method the command will execute. You can also change this delegate type if you need to.
public Action ExecuteDelegate { get; set; }
//You don't have to add a parameter that takes a constructor. I've just added one in case I need access to the window directly.
public WindowCommand(MainWindow window)
{
_window = window;
}
//always called before executing the command, mine just always returns true
public bool CanExecute(object parameter)
{
return true; //mine always returns true, yours can use a new CanExecute delegate, or add custom logic to this method instead.
}
public event EventHandler CanExecuteChanged; //i'm not using this, but it's required by the interface
//the important method that executes the actual command logic
public void Execute(object parameter)
{
if (ExecuteDelegate != null)
{
ExecuteDelegate();
}
else
{
throw new InvalidOperationException();
}
}
}
Nguồn
2016-07-27 00:19:28
Làm cách nào để liên kết lệnh với một mục menu? Chắc chắn đó sẽ là thông tin quan trọng nhất để đưa vào câu trả lời này, nhưng nó bị thiếu. – Timwi
@Timwi: tôi đã sử dụng mã ở trên theo cách này để thêm lối tắt bàn phím vào sự kiện hiện có: RoutedCommand cmndSettings = new RoutedCommand(); cmndSettings.InputGestures.Add (KeyGesture mới (Key.S, ModifierKeys.Control)); CommandBindings.Add (CommandBinding mới (cmndSettings, mnuSettings_Click)); – itsho
nhận xét của itho đã thực hiện công việc này cho tôi, không thể làm cho mã xml ở trên hoạt động. – eightx2