.net - Winform->WPF MVVM 键绑定(bind)错误?

标签 .net wpf mvvm key-bindings winforms-interop

从 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/

相关文章:

wpf - 如何使 ListBoxItem 垂直拉伸(stretch)

c# - Dispatcher.Invoke在vs2010中工作但在vs2008中给出错误

c# - 如何创建新的自定义View(UserControl)?阿瓦隆码头

c# - 如何在 MVVM 之后的 Xamarin.Forms 中将数据从 ViewModel 传递到 View 代码?

C# 从另一个程序启动一个程序

c# - 如何使用内存映射文件进行进程间通信?

c# - 如何为包含 ManualResetEvent.WaitOne() 的异步(套接字)代码编写单元测试?

wpf - 在 WPF 中从 ViewModel 调用 View 的最佳实践

wpf - 在MVVM中以编程方式添加按钮,但Command不起作用

.net - 有没有办法在 C#.NET 中使用 TabIndex 实现通用 KeyDown 处理程序和焦点移动?