在TextBlock中使用绑定的硬编码文本

And*_*ech 51 data-binding wpf xaml textblock

在WPF中,有没有办法让Texta 的属性TextBlock包含硬编码文本和特定绑定?

我想到的是下面的内容(当然,下面没有编译):

<TextBlock Text="Number of Fans: {Binding Artist.Fans.Count}"></TextBlock>
Run Code Online (Sandbox Code Playgroud)

Sco*_*ein 92

如果您使用的是.Net 3.5 SP1

<TextBlock Text="{Binding Path=Artist.Fans.Count, 
                 StringFormat='Number of Fans: {0}'}" />
Run Code Online (Sandbox Code Playgroud)

  • 它丢失了\ {0 \} (5认同)
  • 这是否可以使用多个输出,类似于string.Format([1],[2],[3],... [n])中的args []? (2认同)

小智 36

在使用上述方法时:

<TextBlock Text="{Binding Path="Artist.Fans.Count", 
                  StringFormat='Number of Fans: {0}'}" />
Run Code Online (Sandbox Code Playgroud)

我发现它有点限制,因为我找不到在StringFormat中使用粗体的方法,也不能在StringFormat中使用撇号.

相反,我选择了这种方法,这对我来说效果更好:

<TextBlock TextWrapping="Wrap">
    <Run>The value</Run>
    <Run Text="{Binding Path=MyProperty1, Mode=OneWay}" FontWeight="Bold" />
    <Run>was invalid. Please enter it with the format... </Run>
    <LineBreak/><LineBreak/>
    <Run>Here is another value in the program</Run>
    <Run Text="{Binding Path=MyProperty2, Mode=OneWay}" FontWeight="Bold" />
</TextBlock>                    
Run Code Online (Sandbox Code Playgroud)


Dan*_*bić 6

使用Binding.StringFormat

<TextBlock Text="{Binding Artist.Fans.Count, StringFormat='Number of Fans: {0}'}"/>
Run Code Online (Sandbox Code Playgroud)


rez*_*e08 5

这里绑定值(clouds.all)添加了“%”。您可以在“\{0\}”之后添加您想要的任何值。

 <TextBlock Text="{Binding Path=clouds.all, StringFormat=\{0\}%}"/>
Run Code Online (Sandbox Code Playgroud)