WPF how do I create a textbox dynamically and find the textbox on a button click?

后端 未结 5 882
不思量自难忘°
不思量自难忘° 2021-02-04 04:19

I am creating a TextBox and a Button dynamically using the following code:

Button btnClickMe = new Button();
btnClickMe.Content = \"Cli         


        
5条回答
  •  别那么骄傲
    2021-02-04 04:20

    Josh G had the clue that fixed this code: use RegisterName().

    Three benefits here:

    1. Doesn't use a member variable to save the reference to the dynamically created TextBox.
    2. Compiles.
    3. Complete code.

      using System;
      using System.Windows;
      using System.Windows.Controls;
      
      namespace AddControlsDynamically
      {
          public partial class Window1 : Window
          {
              public void Window_Loaded(object sender, RoutedEventArgs e)
              {
                  GenerateControls();
              }
              public void GenerateControls()
              {
                  Button btnClickMe = new Button();
                  btnClickMe.Content = "Click Me";
                  btnClickMe.Name = "btnClickMe";
                  btnClickMe.Click += new RoutedEventHandler(this.CallMeClick);
                  someStackPanel.Children.Add(btnClickMe);
                  TextBox txtNumber = new TextBox();
                  txtNumber.Name = "txtNumber";
                  txtNumber.Text = "1776";
                  someStackPanel.Children.Add(txtNumber);
                  someStackPanel.RegisterName(txtNumber.Name, txtNumber);
              }
              protected void CallMeClick(object sender, RoutedEventArgs e)
              {
                  TextBox txtNumber = (TextBox) this.someStackPanel.FindName("txtNumber");
                  string message = string.Format("The number is {0}", txtNumber.Text);
                  MessageBox.Show(message);
              }
          }
      }
      

提交回复
热议问题