使用MVVM处理事件的一般方法是将它们简单地包装在Attached Properties中,或使用Attached
Events。这是
PreviewKeyDown在附加属性中使用事件的示例:
public static DependencyProperty PreviewKeyDownProperty = DependencyProperty.RegisterAttached("PreviewKeyDown", typeof(KeyEventHandler), typeof(TextBoxProperties), new UIPropertymetadata(null, OnPreviewKeyDownChanged));public static KeyEventHandler GetPreviewKeyDown(DependencyObject dependencyObject){ return (KeyEventHandler)dependencyObject.GetValue(PreviewKeyDownProperty);}public static void SetPreviewKeyDown(DependencyObject dependencyObject, KeyEventHandler value){ dependencyObject.SetValue(PreviewKeyDownProperty, value);}public static void onPreviewKeyDownChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e){ TextBox textBox = dependencyObject as TextBox; if (e.OldValue == null && e.NewValue != null) textBox.PreviewKeyDown += TextBox_PreviewKeyDown; else if (e.OldValue != null && e.NewValue == null) textBox.PreviewKeyDown -= TextBox_PreviewKeyDown;}private static void TextBox_PreviewKeyDown(object sender, KeyEventArgs e){ TextBox textBox = sender as TextBox; KeyEventHandler eventHandler = GetPreviewKeyDown(textBox); if (eventHandler != null) eventHandler(sender, e);}注意,使用a
ICommand代替实际
KeyEventArgs对象(这实际上不是视图模型中的对象)同样容易(并且也更好)。只需创建类型的附加属性,
ICommand然后从此
TextBox_PreviewKeyDown处理程序中调用它即可:
private static void TextBox_PreviewKeyDown(object sender, KeyEventArgs e){ TextBox textBox = sender as TextBox; ICommand command = PreviewKeyDownCommand(textBox); if (command != null && command.CanExecute(textBox)) command.Execute(textBox);}无论哪种方式,都将使用如下所示的方式:
<TextBox TextBoxProperties.PreviewKeyDown="SomeKeyEventHandler" />
或者,如果您使用了首选
ICommand方法:
<TextBox TextBoxProperties.PreviewKeyDownCommand="{Binding SomeCommand}" />


