栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484002.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号