如何在WPF中的TextBlock的句子中间插入绑定?

dev*_*xer 9 data-binding wpf xaml

我正在寻找这些方面的东西:

<TextBlock
    Grid.Column="1"
    Text="Welcome, {Binding UserName}!" />
Run Code Online (Sandbox Code Playgroud)

这当然会实际向用户显示文本"{Binding UserName}"而不是解码它,但我知道你可以用ASP.NET做这样的事情,所以我希望有一种方法可以让它在WPF.

我已经知道我可以使用IValueConverter...我正在寻找一些我可以做的事情,如果可能的话,我只能在标记中做.

编辑:

基于@Matt Hamilton最优秀的解决方案,我尝试TextBlock使用a 来推动包络并将两个值绑定到相同的位置MultiBinding.奇迹般有效:

<TextBlock
    Style="{StaticResource TextBlock_ValueStyle}"
    Grid.Column="1">
    <TextBlock.Text>
        <MultiBinding
            StringFormat="{}Attempts: {0:G} of {1:G}">
            <Binding
                Path="AttemptNumber" />
            <Binding
                Path="AttemptCount" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

这产生:( Attempts: 1 of 4假设AttemptNumber = 1AttemptCount = 4).

我还发现此链接有助于确定冒号后要放置的格式:

http://msdn.microsoft.com/en-us/library/fbxft59x.aspx

Mat*_*ton 15

您可以在.NET 3.5 SP1中使用StringFormat绑定属性:

<TextBlock Text="{Binding UserName,StringFormat='Welcome, \{0\}!'}" />
Run Code Online (Sandbox Code Playgroud)

请注意,您需要使用反斜杠转义字符串格式的花括号.

更新是,还支持多个值:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="Welcome, {0} {1}!">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)