在运行时将按钮链接到WPF中的文本框

时间:2014-04-14 20:14:54

标签: wpf vb.net wpf-controls textblock

嘿,我已经创建了一些文本框以及在运行时与它们一起使用的按钮。

按钮的代码是:

 Dim updateButton As New Button

 updateButton.Name = "button_" & ticketTheRowNum & "_" & ticketRowNum
 updateButton.Content = "UPDATE!"
 updateButton.Height = 26
 Canvas.SetTop(updateButton, 24 * ticketTheRowNum)
 Canvas.SetLeft(updateButton, 330 + lblNotes.Width)
 updateButton.Width = lblNotes.Width / 2 - 10
 updateButton.Background = New SolidColorBrush(Colors.Green)
 Grid.SetRow(updateButton, 0)
 Grid.SetColumn(updateButton, 0)
 Grid.SetZIndex(updateButton, 2500)
 cavTicket.Children.Add(updateButton)

文本框的代码是:

 Dim txtBlock As New TextBox

 txtBlock.Name = "txt_" & ticketTheRowNum & "_" & ticketRowNum
 txtBlock.Text = theHeader
 txtBlock.TextWrapping = TextWrapping.Wrap
 txtBlock.Width = lblNotes.Width - 5
 txtBlock.BorderThickness = New Thickness(0)
 txtBlock.TextAlignment = TextAlignment.Left
 txtBlock.VerticalScrollBarVisibility = ScrollBarVisibility.Auto
 tmpExpander.Content = txtBlock

现在按钮和文本框在WPF上显示得很好但我不确定如何挂钩按钮以使其知道文本框中的内容并保存其内容。目前,因为我在运行时创建它们,所以如果它在运行之前已经在表单上,​​我就无法访问(我只是简单地调用按钮单击事件然后在其中我会调用文本框内容并保存)。

1 个答案:

答案 0 :(得分:1)

如果你的两个代码块都来自同一个类,那么只需添加一个私有属性txtBlock(顺便说一下为什么阻止而不是Box?)。因此,当您创建TextBox控件时,它将对您的类中的所有函数可见,包括按钮事件处理程序。

但正如NETscape所说。 WPF是关于XAML,绑定和WVVM的。所以,如果你想避免头痛,请使用它们;)