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

WPF C#如何获取GroupBox中前缀相同的TextBox内容?

WPF中获取GroupBox内指定前缀TextBox内容的简洁实现

WPF没有WinForms原生的Controls.Find方法,需要通过递归遍历控件树来定位目标控件,以下是贴合需求的简洁实现方案:

1. 通用控件查找扩展方法

先实现一个可复用的扩展方法,用于递归查找指定类型的子控件:

using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

public static class VisualTreeHelperExtensions
{
    public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject parent) where T : DependencyObject
    {
        if (parent == null) yield break;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            if (child is T targetControl)
                yield return targetControl;

            foreach (var grandChild in FindVisualChildren<T>(child))
                yield return grandChild;
        }
    }
}

2. 业务逻辑实现

利用上述扩展方法,筛选出GroupBox内前缀前5个字符符合要求的TextBox,并完成内容解析:

using System.Globalization;
using System.Linq;
using System.Windows.Controls;

// 假设你的GroupBox实例名为GrpMessage
var targetTextBoxes = GrpMessage.FindVisualChildren<TextBox>()
    // 筛选Name前5个字符匹配的TextBox(示例前缀为"TG_Tx",可根据实际需求修改)
    .Where(txt => txt.Name.Length >= 5 && txt.Name.Substring(0, 5) == "TG_Tx")
    // 按Name中的数字后缀排序(对齐原WinForms循环逻辑)
    .OrderBy(txt => 
    {
        if (int.TryParse(txt.Name.Replace("TG_TxtData", ""), out int index))
            return index;
        return int.MaxValue;
    })
    // 仅取NudLengtht指定数量的TextBox(与原代码逻辑一致)
    .Take((int)NudLengtht.Value)
    .ToList();

byte[] datat = new byte[targetTextBoxes.Count];
for (int i = 0; i < targetTextBoxes.Count; i++)
{
    var textBox = targetTextBoxes[i];
    if (!byte.TryParse(textBox.Text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out datat[i]))
    {
        AddMessage(LstStatus, $"Error converting data to send: {textBox.Text}");
    }
}

关键说明

  • 扩展方法FindVisualChildren无需关注控件层级结构(哪怕后续布局调整也无需修改),通用性更强
  • 通过Linq链式调用完成筛选、排序和数量限制,代码更简洁易读
  • 若前缀字符或TextBox命名规则变化,只需修改Where和OrderBy内的匹配逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:55:08