在WPF,MVVM中实现TextBox LostFocus事件

编程入门 行业动态 更新时间:2024-10-26 08:26:16
本文介绍了在WPF,MVVM中实现TextBox LostFocus事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在我的WPF窗口中实现TextBox LostFocus事件,该事件应该在我的ViewModel中触发,以便我可以验证该值。偶数参数应该传递给命令。如果我们可以使用附加命令行为,那么任何人都可以请分享一个例子。 注意:我使用的是MVVM模式。 问候, Ramana

I want to implement TextBox LostFocus event in my WPF window which should be fired in my ViewModel so that I can validate the value. Even parameter should be passed to the command. If we can use Attached Command Behavior, so anyone can please share an example. Note: I am using MVVM pattern. Regards, Ramana

推荐答案

可以通过创建的附加行为来实现。 Can be achieved by created Attached Behaviour. public class TextBoxBehavior { public static DependencyProperty OnLostFocusProperty = DependencyProperty.RegisterAttached( "OnLostFocus", typeof(ICommand), typeof(TextBoxBehavior), new UIPropertyMetadata(TextBoxBehavior.OnLostFocus)); public static void SetOnLostFocus(DependencyObject target, ICommand value) { target.SetValue(TextBoxBehavior.OnLostFocusProperty, value); } /// <summary> /// PropertyChanged callback for OnDoubleClickProperty. Hooks up an event handler with the /// actual target. /// </summary> private static void OnLostFocus(DependencyObject target, DependencyPropertyChangedEventArgs e) { var element = target as TextBox; if (element == null) { throw new InvalidOperationException("This behavior can be attached to a TextBox item only."); } if ((e.NewValue != null) && (e.OldValue == null)) { element.LostFocus += OnPreviewLostFocus; } else if ((e.NewValue == null) && (e.OldValue != null)) { element.LostFocus -= OnPreviewLostFocus; } } private static void OnPreviewLostFocus(object sender, RoutedEventArgs e) { UIElement element = (UIElement)sender; ICommand command = (ICommand)element.GetValue(TextBoxBehavior.OnLostFocusProperty); if (command != null) { command.Execute(e); } } }

xmlns:ACB="clr-namespace:XML_Binding_Sample1.AttachedCommandBehaviour" <textbox text="{Binding CustomerName}" acb:textboxbehavior.onlostfocus="{Binding NameChangeCommand}" xmlns:acb="#unknown" />

更多推荐

在WPF,MVVM中实现TextBox LostFocus事件

本文发布于:2023-11-11 18:43:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579267.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   MVVM   WPF   LostFocus   TextBox

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!