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>
相关推荐
十月南城2 天前
Flink实时计算心智模型——流、窗口、水位线、状态与Checkpoint的协作
大数据·flink·wpf
听麟5 天前
HarmonyOS 6.0+ 跨端会议助手APP开发实战:多设备接续与智能纪要全流程落地
分布式·深度学习·华为·区块链·wpf·harmonyos
@hdd5 天前
Kubernetes 可观测性:Prometheus 监控、日志采集与告警
云原生·kubernetes·wpf·prometheus
zls3653655 天前
C# WPF canvas中绘制缺陷分布map
开发语言·c#·wpf
专注VB编程开发20年5 天前
c#Redis扣款锁的设计,多用户,多台电脑操作
wpf
闲人编程6 天前
定时任务与周期性调度
分布式·python·wpf·调度·cron·定时人物·周期性
zls3653656 天前
C# WPF canvas中绘制缺陷分布map并实现缩放
开发语言·c#·wpf
数据知道7 天前
PostgreSQL:Citus 分布式拓展,水平分片,支持海量数据与高并发
分布式·postgresql·wpf
闲人编程8 天前
Redis分布式锁实现
redis·分布式·wpf·进程··死锁·readlock
之歆8 天前
ZooKeeper 分布式协调服务完全指南
分布式·zookeeper·wpf