如何在 WPF 中失去焦点时触发文本框命令? [英] How to fire a textbox command upon losing focus in WPF?

查看:46
本文介绍了如何在 WPF 中失去焦点时触发文本框命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户按下 Enter,以下模板可以正常工作,尽管我希望在 TextBox 失去焦点时也触发命令.我怎样才能做到这一点?

The following template works fine if the user presses Enter, although I want the command to fire when the TextBox loses focus as well. How can I do this?

以下是我的TextBox模板

<DataTemplate x:Key="PhantomNameEditTemplate">          
    <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}">
        <TextBox.InputBindings>                 
            <KeyBinding Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=DataContext.RenameCommand}" CommandParameter="{Binding}" Key="Enter" />
        </TextBox.InputBindings>
    </TextBox>
</DataTemplate>

推荐答案

如果您不使用任何 MVVM 框架,您可以使用 System.Windows.Interactivity 执行命令时事件被触发

If you don't use any MVVM framework you could use InvokeCommandAction from System.Windows.Interactivity to execute command when event is fired

<TextBox ...>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="LostFocus">
            <i:InvokeCommandAction 
                Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=DataContext.RenameCommand}" 
                CommandParameter="{Binding}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>

您需要添加对 System.Windows.Interactivity 的引用并在 XAML 中添加命名空间:

you'll need to add reference to System.Windows.Interactivity and add namespace in your XAML:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

这篇关于如何在 WPF 中失去焦点时触发文本框命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆