我正在使用以下代码创建一个 TextBox:
TextBox textBox = new TextBox();
textBox.Name = propertyName;
textBox.Text = value;
textBox.Width = FormControlColumnWidth;
textBox.SetResourceReference(Control.StyleProperty, "FormTextBoxStyle");
sp.Children.Add(textBox); //StackPanel
FormBase.Children.Add(sp);
在点击按钮时,我想获取该文本框的文本值,但我无法在代码中指定:
string firstName = FirstName.Text;
因为“FirstName”将在运行时定义。那么如何在编译时不知道文本框名称的情况下获取文本框的文本值?
以下是我到目前为止的内容,但它说即使在运行时定义它也找不到“FirstName”:
private void Button_Save(object sender, RoutedEventArgs e)
{
using (var db = Datasource.GetContext())
{
var item = (from i in db.Customers
where i.Id == TheId
select i).SingleOrDefault();
item.FirstName = ((TextBox)FindResource("FirstName")).Text;
db.SubmitChanges();
}
}
可复制示例:
我在这里发布了这个问题的完整可重现示例:Why can't I access a TextBox by Name with FindName()? , 也许更容易分析。
最佳答案
最简单的解决方案可能是在代码中的某处保留对文本框的引用。只需添加一个
private TextBox _textbox
在您的类的顶部并将其设置为您在代码中添加的文本框。然后您可以在 Button_Save 事件处理程序中引用它。
关于c# - 如何获取在运行时分配 Name 的 TextBox 的 Text 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1755231/