【问题标题】:how to get value of last text box, that dynamically created如何获取动态创建的最后一个文本框的值
【发布时间】:2018-04-08 22:18:23
【问题描述】:

此代码动态创建一些文本框。 如何在此 UniformGrid 中获取“最后一个”文本框的值? 网络搜索结果不佳!

非常感谢

       public Window1()
        {
            InitializeComponent();    
            for (var i = 0; i < 30; i++)
            {
                uniformGrid.Children.Add(new TextBox
                {
                    Width = 70,
                    Background = Brushes.Beige,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    VerticalContentAlignment = VerticalAlignment.Center,
                    Height = 30,                        
                    Margin = new Thickness(3)
                });
            }            
        }

文本框包含日期,我想获取最后一个文本框的值并显示在带有按钮事件的新文本框中。

private void datePicker_SelectedDateChanged(object sender, RoutedEventArgs e)
        {
            DateTime a = DateTime.Parse(datePicker.Text);
            foreach (Control c in uniformGrid.Children)
            {
                TextBox textbox = c as TextBox;
                if (textbox != null)
                {
                    textbox.Text = a.ToString();
                    a = a.AddDays(1);
                }                
            }
        }


private void button_Click(object sender, RoutedEventArgs e)
{
lasttextBox =...
}

【问题讨论】:

  • 请更新您的问题并提供更多详细信息。您想在哪里访问最后一个文本框?来自另一个类或单击事件或构造函数中的下方?到目前为止,您尝试过什么?
  • 详细来说,究竟是什么为您定义了“最后一个”文本框?它是右下角最远的那个,是日期最新的那个,还是完全不同的。
  • 'last' 是 uniformGrid 中的最终(右下)文本框。假设我们有日期 1 到 30 并且想要获取 30 的日期并显示在新的文本框中。
  • 顺便说一句,你不需要用 foreach 来枚举你正在做的事情。你可以简单地说 foreach (TextBox t in uniformGrid.Children) { ... } 它会隐式地跳过任何其他不同类型的控件。此外,您可以使用 DatePicker 的 SelectedDate 属性而不是解析文本。

标签: c# wpf textbox children


【解决方案1】:

最后一个TextBox 将是您添加的最后一个,因此是Children 集合中的最高索引值。

int lastIndex = uniformGrid.Children.Count - 1;
var lastBox = (TextBox)uniformGrid.Children[lastIndex];

ResultTextBox.Text = lastBox.Text;

如果你有其他控件,那么你只需要枚举文本框(你甚至可以保存结果,因为你在SelectedDateChanged中进行枚举 事件处理程序)。

TextBox lastBox = BoxGrid.Children.OfType<TextBox>().Last();
ResultBox.Text = lastBox.Text;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2014-01-21
    • 2022-01-20
    相关资源
    最近更新 更多