如何使用VB 2008调整字体?

时间:2012-02-09 10:36:58

标签: vb.net visual-studio-2008

我正在使用Visual Studio 2008,我需要能够使用表达式调整字体大小。 到目前为止,我有,

IIf((Len(First(Fields!CardID.Value, "data"))> 30), "12 pt", "72 pt")

我知道我必须引用LEN变量来获得总字符大小,但我不确定如何。

任何建议都将受到赞赏。

提前致谢

1 个答案:

答案 0 :(得分:2)

对于Winforms,下面给出了一个示例。它有点麻烦,但效果很好。对于此示例,有一个带有按钮Button1,文本框TextBox1和标签Label1的表单。单击Button1后,TextBox1中的文字将适合Label1的可用空间。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

  If TextBox1.Text = "" Then
     Exit Sub
  End If

  Dim fnt As New Font("Tahoma", 1, FontStyle.Regular)
  Dim g As Graphics = Me.CreateGraphics

  Dim i As Int32 = 0
  Dim boxWidth As Integer = Label1.Width
  Dim textWidth As Double = 0
  Dim someSmallAmountToAccountForLabelPadding As Int16 = 5

  Do While textWidth < boxWidth - someSmallAmountToAccountForLabelPadding
     i += 1
     fnt = New Font("Tahoma", i, FontStyle.Regular)
     textWidth = g.MeasureString(TextBox1.Text, fnt).Width
  Loop

  Label1.Text = TextBox1.Text
  Label1.Font = fnt

  g.Dispose()

End Sub

enter image description here


对于WPF,您甚至不需要任何代码,只需要一个Viewbox。下面显示的XAML有一个带有TextBox tbx1的窗口和一个TextBlock。无论您在tbx1中输入什么内容,都会自动适应TextBlock,然后Viewbox会向上或向下缩放以适应它所在的可用空间。

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <TextBox Margin="20,8" Name="tbx1"/>
        <Viewbox Grid.Row="1" Stretch="Fill">
            <TextBlock Text="{Binding ElementName=tbx1, Path=Text}" />
        </Viewbox>
    </Grid>

您可以尝试使用Viewbox的Stretch属性来实现不同的效果。 enter image description here

相关问题