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>
相关推荐
bugcome_com1 天前
WPF 核心布局控件全解析:从 Grid 到 UniformGrid 的实战应用
c#·wpf
观无1 天前
WPF-Datagrid控件的无缝滚动
wpf
꧁༺℘₨风、凌๓༻꧂1 天前
C# WPF 项目中集成 Pdf查看器
pdf·c#·wpf
Kiyra2 天前
WebSocket vs HTTP:为什么 IM 系统选择长连接?
分布式·websocket·网络协议·http·设计模式·系统架构·wpf
要记得喝水2 天前
某公司C#-WPF面试题-来自nowcoder(含答案和解析)--2
c#·wpf
Joker 0072 天前
Linux nohup命令实战指南
linux·运维·wpf
时光追逐者2 天前
一个 WPF 开源、免费的 SVG 图像查看控件
开源·c#·.net·wpf
de之梦-御风2 天前
【WebAPI 模拟器】.NET 8/9 + Minimal API + Swagger + DI + WPF Host
.net·wpf·web
Zhen (Evan) Wang2 天前
WPF基于MVVM实现自定义分页控件
wpf