动态添加的控件不可见

时间:2014-02-15 16:49:11

标签: wpf vb.net

我试图动态地向WPF Grid添加控件以创建suduku布局,我已经在调试模式下使用Visual Tree查看器检查,控件正在添加到网格中,但从未在UI上更新,

如果我遗失任何内容,请告诉我。以下是我的代码

    Private Sub MainWindow_Loaded_1(sender As Object, e As RoutedEventArgs)


     For _row As Integer = 0 To 9

        Dim rowDef As RowDefinition = New RowDefinition()


        If _row = 3 Or _row = 6 Then
            grdMain.Height = 25
        Else
            grdMain.Height = 20
        End If
            grdMain.RowDefinitions.Add(rowDef)
        For _col As Integer = 0 To 9

            lblProgress.Content = _row.ToString()
            System.Threading.Thread.Sleep(100)

            Dim colDef As ColumnDefinition = New ColumnDefinition()


            If _col = 3 Or _col = 6 Then
                grdMain.Width = 25
            Else
                grdMain.Width = 20
            End If
                grdMain.ColumnDefinitions.Add(colDef)
            Dim tb As TextBox = New TextBox()
            tb.Name = "txtBox" & _row.ToString & _col.ToString
            tb.Text = tb.Name


            Grid.SetRowSpan(tb, 1)
            Grid.SetColumnSpan(tb, 1)

            grdMain.Children.Add(tb)

            Grid.SetRow(tb, _row)
            Grid.SetColumn(tb, _col)
        Next
    Next
    Me.Content = grdMain
    Me.Show()

End Sub

1 个答案:

答案 0 :(得分:0)

之前没有尝试过,不知道为什么你没有使用xaml来实现这一点。 但是,可以看到遗漏的基本部分是标签的Grid.Row和Grid.Column属性。这需要在您正在创建的行和列中放置一些内容。

例如,要将tb文本框放在第2行和第4列中,您需要执行以下操作:

tb.SetValue(Grid.RowProperty,2);
tb.SetValue(Grid.ColumnProperty,4);

Grid.SetRow(tb, 2);
Grid.SetColumn(tb, 4);