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 控件速查 PDF 笔记(可直接落地版)(带图片)
大数据·microsoft·ui·c#·wpf
张人玉4 小时前
WPF 数据绑定详解
windows·c#·wpf
踏上青云路15 小时前
WPF 避坑指南
wpf
de之梦-御风2 天前
【源码项目】简单实现的WPF浏览器,有兴趣的可以自己扩展(带源码)
wpf
c#上位机2 天前
wpf之数据类型转换
c#·wpf·mvvm
清风徐来Groot2 天前
WPF之布局
wpf
张人玉2 天前
WPF 控件速查 PDF 笔记(可直接落地版)
笔记·microsoft·wpf
“抚琴”的人2 天前
C# 取消机制(CancellationTokenSource/CancellationToken)
开发语言·c#·wpf·1024程序员节·取消机制
清风徐来Groot3 天前
WPF之Style
wpf
rollingman3 天前
WPF GroupBox 淡入淡出
wpf