如何更新在wpf中动态创建的文本框中的文本

时间:2012-06-28 17:49:43

标签: wpf textbox

在WPF中,我动态创建了几个TextBoxes,然后我去找我创建它们的Canvas的所有子对象。当我搜索时,我可以得到文本框的名称,但如何更改文本框中的文本?

我试过了:

// oText is the visual object I found when searching for the textbox
oText.Text = "Software" // doesnt work.
oText.SetValue(control.Text) // doesnt work, because there is no .text property

即使我可以调试它,并将鼠标悬停在oText对象上,然后向下滚动并发现Text属性设置为"Software",但我无法读取它我可以用

oText.GetValue(control.width)

我们如何读取此动态创建的文本框的WPF中的文本值?

以下是代码:

我在XAML中创建了一个画布:

 <Canvas x:Name="Can1" Height="700" Width="874">

        </Canvas>

然后,我制作文本框并将它们放在画布上......

 For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(Can1) - 1
        ' Retrieve child visual at specified index value.
        Dim childVisual As Visual = CType(VisualTreeHelper.GetChild(Can1, i), Visual)
        ' Return the offset vector for the TextBlock object.
        Dim vector As Vector = VisualTreeHelper.GetOffset(childVisual)
        ' Convert the vector to a point value.
        Dim currentPoint As New Point(VisualOffset.X, VisualOffset.Y)
        x = Canvas.GetLeft(childVisual)
        y = Canvas.GetTop(childVisual)

        A = childVisual.GetValue(Control.ActualHeightProperty)
        B = childVisual.GetValue(Control.ActualWidthProperty)     

        Dim myTextbox As New TextBox
        Dim c As Int16
        myTextbox.Width = B
        myTextbox.Text = "Software"
        myTextbox.Name = "TextB" & i.ToString
        Can1.Children.Add(myTextbox)
        Canvas.SetTop(myTextbox, y + A)
        Canvas.SetLeft(myTextbox, x)
        Canvas.SetZIndex(myTextbox, 0)
next i

然后,我使用主窗口上的按钮来调用GetData ...

Private Sub GetData(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    Dim iCount As Int16
    Dim oText As Visual
    Dim sTemp As String
    Dim cs = My.Settings.ConnectionString
    Dim oConn = New SqlConnection(cs)
    Dim cmd As New SqlCommand()
    Text1.text = ""
    cmd.Connection = oConn
    Try
        oConn.Open()
        cmd.CommandText = "select top 5 finumber from fiheading "
        Dim myReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        While myReader.Read()
            iCount += 1
            oText = FindChild(Can1, "TextB" & iCount.ToString)
            'sTemp = oText.GetValue(Control.NameProperty)
            'oText.text = (myReader.GetString(0))
            'oText.SetValue(Control.text)

        End While
        myReader.Close()
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try


    Try
        oConn.Close()
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try


End Sub

1 个答案:

答案 0 :(得分:1)

oText被定义为Visual,没有Text属性

将其更改为TextBox并将FindChild的结果投放到TextBox,它应该可以正常工作

Dim oText As TextBox
...

oText = CType(FindChild(Can1, "TextB" & iCount.ToString), TextBox)