【问题标题】:Are the names of the textboxes inside a stack panel global variables?堆栈面板中的文本框名称是全局变量吗?
【发布时间】:2019-08-17 13:21:03
【问题描述】:

我想动态创建一系列 StackPanel,其中包括几个 TextBox 和 TextBlock。我需要能够获取它们的值,所以我必须使它们的名称全局唯一还是在 StackPanel 中唯一?

【问题讨论】:

  • 你真正想要的是一个 ItemsControl,它的 ItemTemplate 中有 StackPanel。 ItemsSource 属性将绑定到具有 TextBlocks 和 TextBoxes 绑定到的属性的数据项对象的集合。见Data Templating Overview

标签: c# wpf xaml naming


【解决方案1】:

您无法像普通的TextBox 那样访问添加到StackPanel 子集合中的TextBoxes。但是您可以通过它们的名称获取它们的值,如下所示:

private static string GetChildValue(Panel panel, string name)
{
    var children = panel.Children;

    foreach (var child in children)
    {
        if (!(child is TextBox))
            continue;

        var textBox = (TextBox)child;
        if (textBox.Name.Equals(name))
            return textBox.Text;
    }

    return string.Empty;
}

private static void DoSomething()
{
    var stackPanel = new StackPanel();
    stackPanel.Children.Add(new TextBox { Name = "TextBox1", Text = "TextBox1 Value" });
    stackPanel.Children.Add(new TextBox { Name = "TextBox2", Text = "TextBox2 Value" });
    stackPanel.Children.Add(new TextBox { Name = "TextBox3", Text = "TextBox3 Value" });
    stackPanel.Children.Add(new TextBox { Name = "TextBox4", Text = "TextBox4 Value" });

    var textBox1Value = GetChildValue(stackPanel, "TextBox1");
}

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 2013-06-27
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2019-04-13
    • 1970-01-01
    • 2017-11-05
    相关资源
    最近更新 更多