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

  • 代码 

<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

<TextBox Text="{Binding Path=UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

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

<TextBox Text="{Binding Path=UserName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />

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

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

然后在代码中调用:

var bindingExpression = myTextBox.GetBindingExpression(TextBox.TextProperty);
bindingExpression.UpdateSource();

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

  • 允许回车换行

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

<TextBox AcceptsReturn="True">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding SendMessageFunCommand}"
                    Key="Enter"
                    Modifiers="Ctrl"/>
    </TextBox.InputBindings>
</TextBox>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z_W_H_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值