从 WinForm 应用程序调用 WPF KeyBindings 时,我需要一些帮助。我已经创建了我认为是演示问题的基本部分。如果有帮助,我可以提供一个示例应用程序。
WinForm 应用程序启动一个表单,该表单有一个调用 WPF 的按钮
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim view As New WpfPart.MainWindow
System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(view)
view.ShowDialog()
End Sub
使用 WPF View 创建它的 View 模型并设置键控:
<Window x:Class="WpfPart.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfPart.ViewModels"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<Window.InputBindings>
<KeyBinding Key="Escape" Command="{Binding OpenCommand}" Modifiers="Control" />
</Window.InputBindings>
<Grid>
</Grid>
ViewModel 使用 DelagateCommand 希望将所有内容链接起来
using System;
using System.Windows;
using System.Windows.Input;
using WpfPart.Commands;
namespace WpfPart.ViewModels
{
class MainWindowViewModel
{
private readonly ICommand openCommand;
public MainWindowViewModel()
{
openCommand = new DelegateCommand(Open, CanOpenCommand);
}
public ICommand OpenCommand { get { return openCommand; } }
private bool CanOpenCommand(object state)
{
return true;
}
private void Open(object state)
{
MessageBox.Show("OpenCommand executed.");
}
}
}
谁能看到哪里出了问题,按键什么也没做?!?
最佳答案
要使 KeyBinding 工作,您需要将 CommandReference 添加到 Window.Resources,然后从 KeyBinding(而不是 Command)引用 CommandReference。
我还使用 Control-X 来避免在 Windows 中打开映射到 Control-Escape 的“开始”按钮。
这是您可以根据您的问题使用的 XAML:
<Window.Resources>
<!-- Allows a KeyBinding to be associated with a command defined in the View Model -->
<c:CommandReference x:Key="OpenCommandReference" Command="{Binding OpenCommand}" />
</Window.Resources>
<Window.InputBindings>
<KeyBinding Key="X" Command="{StaticResource OpenCommandReference}" Modifiers="Control" />
</Window.InputBindings>
关于.net - Winform->WPF MVVM 键绑定(bind)错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3868812/