了解为什么WPF KeyBinding在测试中工作但在winforms应用程序中不工作

时间:2011-03-18 09:57:53

标签: wpf binding

我有一个最顶层的对话框,当有人按下按钮或点击逃生时,它会自动隐藏。

(显示的代码是一个非常简化的版本,以突出遇到的问题。)

如果我按如下方式启动对话框,一切正常。

var dialog = new MyDialog(new MyDialogViewModel());
new Application().Run(dialog);

如果我按如下方式打开对话框,则转义键绑定将不起作用,但按钮仍然有效。

new MyDialog(new MyDialogViewModel()).Show();

MyDialog.xaml

<Window x:Class="MyDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
    Topmost="True"
    Visibility="{Binding Visibility}">

    <Window.InputBindings>
        <KeyBinding Key="Escape" Command="{Binding HideCommand}" />
    </Window.InputBindings>

    <Button Command="{Binding HideCommand}">Hide</Button>
</Window>

MyDialog.xaml.cs

public partial class MyDialog : Window
{
    public MyDialog(MyDialogViewModel vm)
    {
        DataContext = vm;
        InitializeComponent();
    }
}

MyDialogViewModel.cs

public class MyDialogViewModel : INotifyPropertyChanged
{
    private Visibility _visibility = Visibility.Visible;

    public MyDialogViewModel()
    {
        HideCommand = new DelegateCommand(Hide);
    }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public DelegateCommand HideCommand { get; private set; }

    public Visibility Visibility 
    { 
        get
        {
            return _visibility;
        }
        set 
        { 
            _visibility = value;
            PropertyChanged();
        }
    }

    private void Hide()
    {
        Visibility = Visibility.Hidden;
    }
}

使用Snoop我可以看到以下绑定错误,无论哪种方式启动都会出现这种情况。

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=HideCommand; DataItem=null; target element is 'KeyBinding' (HashCode=30871361); target property is 'Command' (type 'ICommand')

我试图理解为什么转义键在一个场景中工作而不在另一个场景中。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

一些想法/问题:

  1. 在不起作用的版本中,您在哪里打开对话框?从应用程序启动的主窗口?

  2. 在MyDialog构造函数中,我假设您调用了InitializeComponent。那是对的吗?否则,它将无法从XAML文件中正确初始化。

  3. 您是否有理由不能使用Button.IsCancel属性?

  4. 编辑:

    如果从WinForms应用程序加载WPF窗口,则需要做一些额外的工作。 This blog解释了这一点并包含以下示例:

    using System;
    using System.Windows.Forms;
    using System.Windows.Forms.Integration;
    ....
    var wpfwindow = new WPFWindow.Window1();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.Show();
    

答案 1 :(得分:1)

我想知道它是否是KeyBinding的计时问题。我刚检查了一个有大量KeyBinding的项目,命令都是静态的,所以没有问题。我想知道在更新VM之前是否发生了KeyBinding命令绑定,并且永远不会更新绑定。

更新:检查一下,它可能是答案: http://joyfulwpf.blogspot.com/2009/05/mvvm-commandreference-and-keybinding.html

并且: Keybinding a RelayCommand