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

后端 未结 5 964
不思量自难忘°
不思量自难忘° 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:42

    Is there any way you can make the TextBox control a field in your class instead of a variable inside your generator method

    public class MyWindow : Window
    {
        private TextBox txtNumber;
    
        public void Window_Loaded()
        {
            GenerateControls();
        }
    
        public void GenerateControls()
        {
            Button btnClickMe = new Button();
            btnClickMe.Content = "Click Me";
            btnClickMe.Name = "btnClickMe";
            btnClickMe.Click += new RoutedEventHandler(this.CallMeClick);
            someStackPanel.Childern.Add(btnClickMe);
            txtNumber = new TextBox();
            txtNumber.Name = "txtNumber";
            txtNumber.Text = "1776";
            someStackPanel.Childern.Add(txtNumber);
        }
    
        protected void ClickMeClick(object sender, RoutedEventArgs e)
        {    
            // Find the phone number    
            string message = string.Format("The number is {0}", txtNumber.Text);        
            MessageBox.Show(message);
        }
    }
    

提交回复
热议问题