[WPF]TextBox 实现Enter事件

TextBox 实现Enter事件

Window页面Xmal

复制代码
<Window x:Class="TextBoxEnter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="205" Width="338">
    <Grid Margin="0,0,0,0">

        <TextBox Width="100" Height="30" Text="{Binding TextContent, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
            <TextBox.InputBindings>
                <KeyBinding Command="{Binding EnterCommand}" Key="Enter"/>
            </TextBox.InputBindings>
        </TextBox>
    </Grid>
</Window>
复制代码

绑定DataContext

复制代码
using System.Windows;

namespace TextBoxEnter
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainVm();
        }
    }
}
复制代码

ViewModel逻辑 使用Prism框架实现Command 及 Binding

复制代码
using Prism.Commands;
using Prism.Mvvm;
using System.Windows.Input;

namespace TextBoxEnter
{
    class MainVm : BindableBase
    {
        private int num = 0;

        private string textContent;

        public string TextContent
        {
            get { return textContent; }
            set { SetProperty(ref textContent, value); }
        }


        private ICommand enterCommand;
        public ICommand EnterCommand
        {
            get
            {
                if (enterCommand == null)
                {
                    enterCommand = new DelegateCommand(() => { TextContent = "Enter: " + num++ + " times"; });
                }
                return enterCommand;
            }
        }
    }
}
复制代码

效果,光标选中TextBox,按下回车,触发Command事件,更新Text内容 

 

posted @   xiaoshuye  阅读(2058)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示