WPF TextBox实现键盘enter后实时读取TextBox中的值

代码

XML 复制代码
<TextBox Grid.Column="0" x:Name="textBox" Margin="10,5,0,5" TextWrapping="Wrap" Text="{Binding SendMessage,UpdateSourceTrigger=PropertyChanged}" 
         VerticalContentAlignment="Center" CaretBrush="Green" BorderBrush="{DynamicResource background_brush}" BorderThickness="0" FontSize="15" Padding="0" MinHeight="25" MaxHeight="150" 
         ScrollViewer.VerticalScrollBarVisibility="Auto" AcceptsReturn="True">
    <TextBox.Resources>
        <Style TargetType="{x:Type Border}">
            <Setter Property="CornerRadius" Value="2"/>
        </Style>
    </TextBox.Resources>
    <TextBox.InputBindings>
        <!--键盘事件绑定-->
        <KeyBinding Command="{Binding SendMessageFunCommand}" Key="Enter" Modifiers="Ctrl"/>
    </TextBox.InputBindings>
</TextBox>

UpdateSourceTrigger解释

如果你想在用户输入时立即更新数据源,可以将UpdateSourceTrigger设置为PropertyChanged

XML 复制代码
<TextBox Text="{Binding Path=UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

如果希望在TextBox失去焦点时更新数据源,可以将UpdateSourceTrigger设置为LostFocus(这是默认值):

XML 复制代码
<TextBox Text="{Binding Path=UserName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />

如果需要手动控制更新时机,可以将UpdateSourceTrigger设置为Explicit,并在代码中调用UpdateSource方法:

XML 复制代码
<TextBox x:Name="myTextBox" Text="{Binding Path=UserName, Mode=TwoWay, UpdateSourceTrigger=Explicit}" />

然后在代码中调用:

复制代码
var bindingExpression = myTextBox.GetBindingExpression(TextBox.TextProperty);
bindingExpression.UpdateSource();

通过这些方法,你可以灵活地控制TextBox数据绑定的更新时机。

允许回车换行

若需同时支持Enter键换行和提交,可通过AcceptsReturnInputBindings区分行为:

XML 复制代码
<TextBox AcceptsReturn="True">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding SendMessageFunCommand}"
                    Key="Enter"
                    Modifiers="Ctrl"/>
    </TextBox.InputBindings>
</TextBox>
相关推荐
Macbethad17 小时前
技术方案:工业控制系统架构设计
wpf
狮恒1 天前
OpenHarmony Flutter 分布式数据持久化:跨设备数据一致性与同步方案
分布式·flutter·wpf·openharmony
狮恒1 天前
OpenHarmony Flutter 分布式数据管理:跨设备数据同步与一致性保障方案
分布式·flutter·wpf·openharmony
Macbethad1 天前
工业设备IO模拟程序
wpf
狮恒2 天前
OpenHarmony Flutter 分布式设备发现与连接:无感组网与设备协同管理方案
分布式·flutter·wpf·openharmony
云和数据.ChenGuang2 天前
鸿蒙负一屏的技术定位与核心价值
华为·wpf·harmonyos
狮恒2 天前
OpenHarmony Flutter 分布式数据管理实战:全场景数据一致性与高效流转方案
wpf
狮恒2 天前
OpenHarmony Flutter 分布式音视频:跨设备流传输与实时协同交互方案
分布式·flutter·wpf·openharmony
狮恒2 天前
OpenHarmony Flutter 分布式安全与隐私保护:跨设备可信交互与数据防泄漏方案
分布式·flutter·wpf·openharmony
狮恒2 天前
OpenHarmony Flutter 分布式智能协同:基于 AI 的跨端场景感知与自适应交互方案
wpf