使用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);
}
注意,它也很容易(和更好的太)使用的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}" />
Google用于交互触发器。 –
或者只是将视图的DataContext转换为ViewModel并做任何您想要做的事情.ViewModel vm = this.DataContext as ViewModel;那么你可以做vm。SomeAction – Krishna
@RohitVats谢谢,我看到在一些例子中使用它们,但它看起来并不像我所需要的。现在我发现我错了。 – Kurtevich