本文介绍了WPF中如何动态创建一个文本框,并找到一个按钮,点击文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我动态创建一个文本框
和按钮使用下列code:
I am creating a TextBox
and a Button
dynamically using the following code:
Button btnClickMe = new Button();
btnClickMe.Content = "Click Me";
btnClickMe.Name = "btnClickMe";
btnClickMe.Click += new RoutedEventHandler(this.CallMeClick);
someStackPanel.Childern.Add(btnClickMe);
TextBox txtNumber = new TextBox();
txtNumber.Name = "txtNumber";
txtNumber.Text = "1776";
someStackPanel.Childern.Add(txtNumber);
我钩到click事件的点击我的
按钮。点击我的按钮,即使是正确的解雇。不过,我无法找到文本框
我动态输入。
I hook up to a click event to the Click Me
button. The click me button even is fired correctly. However I cannot find the TextBox
I entered dynamically.
下面是我点击我的事件:
Here is my click me event:
protected void ClickMeClick(object sender, RoutedEventArgs e)
{
// Find the phone number
TextBox txtNumber = this.someStackPanel.FindName("txtNumber") as TextBox;
if (txtNumber != null)
{
string message = string.Format("The number is {0}", txtNumber.Text);
MessageBox.Show(message);
}
else
{
MessageBox.Show("Textbox is null");
}
}
我如何找到文本框
txtNumber
?
推荐答案
乔希G的是修复了这个code线索:使用RegisterName()
Josh G had the clue that fixed this code: use RegisterName().
三惠在这里:
- 不使用一个成员变量来保存参照动态创建的文本框。
- 编译。
-
完成code。
- Doesn't use a member variable to save the reference to the dynamically created TextBox.
- Compiles.
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);
}
}
}
这篇关于WPF中如何动态创建一个文本框,并找到一个按钮,点击文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!