将事件传递给ViewModel的最佳方法是什么?

情况是:我有一个控件的事件,我想让我的ViewModel做出反应。目前,我正在通过执行不可见按钮的命令来执行此操作,如以下示例所示。

在View.xaml中:

<Control x:Name="SearchResultGrid" ... DataRefreshed="SearchResultRefreshed" />

<Button x:Name="SearchResultRefreshedButton" Visibility="Collapsed" Command="{Binding SearchResultRefreshedCommand}" />

在View.xaml.cs中:

private void SearchResultRefreshed(object sender, EventArgs e)

{

if (SearchResultRefreshedButton.Command != null)

{

SearchResultRefreshedButton.Command.Execute(SearchResultGrid.ResultRowCount);

}

}

这很好用,但对我来说似乎是hack。我想知道是否有更好的(标准)方法?我找不到任何示例,这就是我自己“发明”的。

回答:

使用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}" />

以上是 将事件传递给ViewModel的最佳方法是什么? 的全部内容, 来源链接: utcz.com/qa/406937.html

回到顶部