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>
相关推荐
玉面小君3 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:Trigger、MultiTrigger、DataTrigger 的迁移
wpf·avalonia
招风的黑耳3 天前
Java生态圈核心组件深度解析:Spring技术栈与分布式系统实战
java·spring·wpf
lfw20194 天前
WPF 数据绑定模式详解(TwoWay、OneWay、OneTime、OneWayToSource、Default)
wpf
Magnum Lehar4 天前
3d wpf游戏引擎的导入文件功能c++的.h实现
3d·游戏引擎·wpf
FuckPatience4 天前
WPF Telerik.Windows.Controls.Data.PropertyGrid 自定义属性编辑器
wpf
almighty275 天前
C#WPF控制USB摄像头参数:曝光、白平衡等高级设置完全指南
开发语言·c#·wpf·usb相机·参数设置
军训猫猫头5 天前
12.NModbus4在C#上的部署与使用 C#例子 WPF例子
开发语言·c#·wpf
我要打打代码5 天前
在WPF项目中使用阿里图标库iconfont
wpf
拾忆,想起6 天前
Redisson 分布式锁的实现原理
java·开发语言·分布式·后端·性能优化·wpf
weixin_464078076 天前
wpf依赖注入驱动的 MVVM实现(含免费源代码demo)
wpf