【问题标题】:Having hardcoded text with a binding in a TextBlock在 TextBlock 中使用绑定的硬编码文本
【发布时间】:2010-10-21 19:30:40
【问题描述】:

在 WPF 中,有没有办法让 TextBlockText 属性同时包含硬编码文本和特定绑定?

我想到的是以下内容(当然,以下内容无法编译)

<TextBlock Text="Number of Fans: {Binding Artist.Fans.Count}"></TextBlock>

【问题讨论】:

    标签: wpf xaml data-binding textblock


    【解决方案1】:

    在使用上述方法时:

    <TextBlock Text="{Binding Path="Artist.Fans.Count, 
                      StringFormat='Number of Fans: {0}'}" />
    

    我发现它有些限制,因为我找不到在 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>                    
    

    【讨论】:

    • ...或在同一个TextBlock中使用2个绑定
    【解决方案2】:

    使用模板 10 和 MVVM 的 XAML:

    要明确一点:

    • 根据定义,绑定将值绑定到控件的属性。
    • 在“模板 10”框架中实现的 MVVM 范例下,值在与相关 XAML 页面关联的 ViewModel 中初始化。

    以下是如何将硬编码文本与 Text 属性中的绑定一起使用:

        <Page
            ...
            xmlns:vm="using:doubleirish.ViewModels"
            xmlns:sys="using:System"
            xmlns:controls="using:Template10.Controls"
            ...
    
            <Page.DataContext>
                <vm:StocksViewModel x:Name="ViewModel" />
            </Page.DataContext>
    
            ...
    
            <controls:PageHeader ... Text="{x:Bind sys:String.Format('Ticker : {0}', ViewModel.Ticker)}">
    
        ...
    
        </Page>
    

    【讨论】:

      【解决方案3】:

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

       <TextBlock Text="{Binding Path=clouds.all, StringFormat=\{0\}%}"/>
      

      【讨论】:

      • 能否请您 edit 解释为什么这段代码回答了这个问题?纯代码答案是 discouraged,因为它们不教授解决方案。
      • @Nathan 我编辑我的答案。现在有用吗?感谢您的建议。
      【解决方案4】:

      有,如果您使用的是 .Net 3.5 SP1

      <TextBlock Text="{Binding Path=Artist.Fans.Count, 
                       StringFormat='Number of Fans: {0}'}" />
      

      【讨论】:

      • 这样是否可以使用多个输出,类似于string.Format([1], [2], [3],...[n])中的args[]?
      • 缺少转义 \{0\}
      【解决方案5】:

      使用Binding.StringFormat:

      <TextBlock Text="{Binding Artist.Fans.Count, StringFormat='Number of Fans: {0}'}"/>
      

      【讨论】:

      • 嗨 Danko - 你知道如何使用属性元素语法吗?
      猜你喜欢
      • 2013-01-15
      • 2011-03-09
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 2011-01-01
      • 2019-04-02
      • 1970-01-01
      • 2012-03-20
      相关资源
      最近更新 更多