在WPF,MVVM中实现TextBox LostFocus事件 [英] mplement TextBox LostFocus event in WPF , MVVM
本文介绍了在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事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文