【发布时间】:2011-03-18 09:57:53
【问题描述】:
我有一个最顶层的对话框,当有人按下按钮或点击退出时,它会自行隐藏。
(显示的代码是一个非常简化的版本,以突出遇到的问题。)
如果我按如下方式启动对话框,一切正常。
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')
我试图理解为什么转义键在一种情况下有效,而在另一种情况下无效。有什么想法吗?
【问题讨论】: