在运行时创建TextBlock

时间:2013-01-07 09:50:51

标签: vb.net wpf-controls runtime textblock

我正在尝试在运行时使用自动换行创建复选框。带有自动换行的复选框的XAML如下所示:

<CheckBox Width="140" Height="35">
    <ContentControl>
        <TextBlock TextWrapping="Wrap">This is a long text with word wrap</TextBlock>
    </ContentControl>
</CheckBox>

现在我想用代码创建这个XAML,但我不知道如何让它工作。我可以创建复选框并将其添加到现有的WrapPanel,但textBlock控件没有content属性。如何将内容添加到textBlock以及如何将两者(contentControl和textBlock)添加到复选框?

For intIndex = 0 To m_aryActions.Length - 1

    Dim textBlock As TextBlock = New TextBlock
    Dim contentControl As ContentControl = New ContentControl
    Dim checkBox As CheckBox = New CheckBox

    textBlock.TextWrapping = TextWrapping.Wrap
    contentControl.Content = textBlock

    With checkBox
        .Width = 140
        .Height = 25
        .Name = "CheckBox" & intIndex
    End With

    WrapPanel.Children.Add(checkBox)

Next

谢谢, 彼得

1 个答案:

答案 0 :(得分:0)

好的,自己找吧:

Dim textBlock As TextBlock = New TextBlock
Dim contentControl As ContentControl = New ContentControl
Dim checkBox As CheckBox = New CheckBox

With textBlock
    .TextWrapping = TextWrapping.Wrap
    .Text = m_aryWishes(intIndex)
End With

contentControl.Content = textBlock

With checkBox
    .Width = intWidth
    .Height = intHeight
    .Content = contentControl
    .Name = "CheckBox" & intIndex
    .Padding = New System.Windows.Thickness(10, 0, 20, 0)
    .Focusable = False
    .ClickMode = ClickMode.Press
End With

WrapPanel.Children.Add(checkBox)