使用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