如何在WPF中失去焦点时触发文本框命令?

Bob*_*Bob 0 c# wpf xaml

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

以下是我的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>
Run Code Online (Sandbox Code Playgroud)

dko*_*ozl 5

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

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