You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI3 .NET中TextBox是否有onFocused事件?如何实现点击/聚焦改文本?

TextBox点击/获焦时修改文本的实现方案

根据不同的技术栈,以下是具体实现方式:

WinForms 实现

可以通过GotFocus(获焦)或MouseClick(鼠标点击)事件来完成需求:

  1. 绑定事件(代码或设计器绑定均可)
public Form1()
{
    InitializeComponent();
    // 绑定获焦事件
    textBox1.GotFocus += TextBox1_GotFocus;
    // 绑定左键点击事件
    textBox1.MouseClick += TextBox1_MouseClick;
}
  1. 事件处理方法
// 获焦时修改文本
private void TextBox1_GotFocus(object sender, EventArgs e)
{
    var textBox = sender as TextBox;
    if (textBox != null)
    {
        // 可添加判断逻辑,比如仅当文本为默认值时修改
        if (textBox.Text == "请输入内容")
        {
            textBox.Text = "";
        }
        else
        {
            textBox.Text = "获焦后更新的文本";
        }
    }
}

// 左键点击时修改文本
private void TextBox1_MouseClick(object sender, MouseEventArgs e)
{
    var textBox = sender as TextBox;
    if (textBox != null && e.Button == MouseButtons.Left)
    {
        textBox.Text = "左键点击后更新的文本";
    }
}

WPF 实现

使用GotFocus事件或PreviewMouseLeftButtonDown事件:

  1. XAML 绑定事件
<TextBox x:Name="myTextBox" 
         GotFocus="MyTextBox_GotFocus" 
         PreviewMouseLeftButtonDown="MyTextBox_PreviewMouseLeftButtonDown"
         Text="默认提示文本"/>
  1. 后台处理代码
private void MyTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    var textBox = sender as TextBox;
    textBox.Text = "WPF获焦后更新的文本";
}

private void MyTextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var textBox = sender as TextBox;
    // 先让文本框获焦,再修改内容
    textBox.Focus();
    textBox.Text = "WPF左键点击后更新的文本";
}

Web 前端(HTML+JS)实现

通过focus或click事件实现:

  1. HTML 结构
<input type="text" id="myInput" value="请输入内容">
  1. JavaScript 处理
const input = document.getElementById('myInput');

// 获焦事件
input.addEventListener('focus', function() {
    // 仅默认文本时清空
    if (this.value === "请输入内容") {
        this.value = "";
    } else {
        this.value = "获焦后更新的文本";
    }
});

// 左键点击事件
input.addEventListener('click', function(e) {
    // e.button===0 代表左键
    if (e.button === 0) {
        this.value = "左键点击后更新的文本";
    }
});

内容的提问来源于stack exchange,提问作者Ростислав Романець

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:13:13