首页 > 解决方案 > 按下按钮时WPF失去焦点不会触发

问题描述

这是用于输入/选择 IP 的可编辑组合框的 XAML 代码。

<ComboBox Name="ComboBoxServerIp" 
    Grid.Row="2"  Grid.Column="1"                                                            
    ItemsSource="{Binding ServerList}"          
    Text="{Binding SelectedServer, UpdateSourceTrigger=LostFocus, Mode=TwoWay}"
    IsEditable="True" IsReadOnly="False">
    <ComboBox.InputBindings>
        <KeyBinding Command="{Binding UpdateServerIpCommand}" Key="Enter"
                    CommandParameter="{Binding ElementName=ComboBoxServerIp ,Path=Text}"/>
    </ComboBox.InputBindings>   
</ComboBox>

一旦用户完成输入 IP,它就会触发一个大约需要 10 秒的流程。所以我使用了 lostfocus 和 enter 键的组合来触发更新。

除了用户在没有首先失去焦点或按下回车的情况下按下按钮的用例之外,这很好用。在这种情况下, SelecterServer 更新不会在按钮的命令执行之前触发。该命令读取旧的 SelectedServer 值。不是 UI 中的那个

tl;dr - 在 UI 中按下按钮时,文本框中不会触发 lostfocus 事件。如何从 UI 端强制更新?

标签: wpfmvvm

解决方案


发现了一个完全相反的问题, WPF Lost-Focus issue in same control的帖子。

令人惊讶的是,该修复的反面对我来说非常有效,将此属性添加到按钮:

Focusable="False"

lostFocus 事件在按钮单击事件之前触发。一切都按预期工作。


推荐阅读