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

C#实现点击按钮将TextBox输入文本移至指定TextBlock的方法

修正WPF按钮点击事件的文本更新问题

嗨,我看了你的代码,问题出在执行顺序搞反了!你先把commentTextbox.Text清空了,再去把它的值追加到menuText里,这时候TextBox已经是空的了,自然看不到任何内容更新。

先看看你现有代码的问题所在:

private void commentButton_Click(object sender, RoutedEventArgs e) {
if (string.IsNullOrWhiteSpace(commentTextbox.Text)) { }
else {
commentTextbox.Text = string.Empty;
menuText.Text += commentTextbox.Text;
}
}

这段代码里,commentTextbox.Text = string.Empty;先执行,直接把输入框的内容清空了,之后menuText.Text += commentTextbox.Text;其实是给TextBlock追加了一个空字符串,完全起不到更新内容的作用。

下面是修正后的代码:

private void commentButton_Click(object sender, RoutedEventArgs e)
{
    // 先判断输入是否有效(非空/非空白)
    if (!string.IsNullOrWhiteSpace(commentTextbox.Text))
    {
        // 第一步:把用户输入的内容追加到目标TextBlock
        menuText.Text += commentTextbox.Text;
        // 第二步:清空输入用的TextBox
        commentTextbox.Text = string.Empty;
    }
    // 如果需要,这里可以加个输入为空时的提示逻辑,比如弹出提示框
}

只需要把追加文本到TextBlock和清空TextBox的顺序调换一下就搞定了——先把用户输入的内容取出来更新到menuText,再清空输入框,这样就能完美实现你要的需求。如果希望每条评论换行显示,还可以在追加的时候加个换行符,比如改成:

menuText.Text += commentTextbox.Text + Environment.NewLine;

内容的提问来源于stack exchange,提问作者jlhoh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:31:47