在Textblock xaml中显示带有字符串的文本

时间:2013-03-03 12:06:50

标签: wpf vb.net xaml

我有一个文本块,我想显示一个带有已定义字符串的文本。怎么做?

文本块:

 <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Padding="6" VerticalAlignment="Center" Margin="45,0,0,0" Height="30" Width="386" Text="My Program ver. Version"/>

我的字符串:

Public Version As String = "1.0a"

3 个答案:

答案 0 :(得分:4)

您可以使用StringFormat

<TextBlock Text="{Binding Path=Version, StringFormat=My Program ver. {0}}" />

在您的代码隐藏中,您必须将Version更改为property(此属性应为ReadOnly,因为它在运行时不会更改)并在构造函数中指定DataContext

Class MainWindow 

    Public Sub New()
        InitializeComponent()
        Me.DataContext = Me
    End Sub

    ReadOnly Property Version As String
        Get
            Return "1.0a"
        End Get
    End Property
End Class

答案 1 :(得分:1)

如果您希望TextBlock在每次有新版本时更新版本号,请执行以下操作: 你可以在C#中这样做。您可以很容易地找到如何在VB中编写它。

每次发布​​程序的新版本时,都会更新TextBlock。

在XAML中,您将TextBlock文本绑定到“Version”:

<TextBlock Text="{Binding Version, Mode=OneWay}" />`

然后在代码隐藏或视图模型中,您可以使用XAML TextBlock中的Binding属性:

    public string Version
    {
        get
        {
          return String.Format("VERSION: {0}",DeploymentInfo.Version.ToString());
        }
    }

然后,您需要在项目中添加对 “System.Deployment” 的引用。

只有在完成项目的“发布”后才能使用此功能。启动调试器时,您可能只会看到版本号:0.0.0.0

答案 2 :(得分:0)

在XAML文件中:

首先,您应该为我的TextBlock命名,例如我已经给了tbWithNoName

<TextBlock x:Name="tbWithNoName" HorizontalAlignment="Left" TextWrapping="Wrap" Padding="6" VerticalAlignment="Center" Margin="45,0,0,0" Height="30" Width="386" Text="My Program ver. Version"/>

然后在Window对象上添加Loaded调用。

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
        Loaded="Window_Loaded">

将Window_Loaded函数插入vb文件。

Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
    tbWithNoName.Text = tbWithNoName.Text + " " + Version
End Sub

这将在加载窗口时更改TextBlock的文本

相关问题