Use StringFormat to add a string to a WPF XAML binding

后端 未结 4 1136
一向
一向 2020-11-28 04:14

I have a WPF 4 application that contains a TextBlock which has a one-way binding to an integer value (in this case, a temperature in degrees Celsius). The XAML looks like t

相关标签:
4条回答
  • 2020-11-28 04:49

    Your first example is effectively what you need:

    <TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />
    
    0 讨论(0)
  • 2020-11-28 04:50

    In xaml

    <TextBlock Text="{Binding CelsiusTemp}" />
    

    In ViewModel, this way setting the value also works:

     public string CelsiusTemp
            {
                get { return string.Format("{0}°C", _CelsiusTemp); }
                set
                {
                    value = value.Replace("°C", "");
                  _CelsiusTemp = value;
                }
            }
    
    0 讨论(0)
  • 2020-11-28 04:52

    Please note that using StringFormat in Bindings only seems to work for "text" properties. Using this for Label.Content will not work

    0 讨论(0)
  • 2020-11-28 05:09

    Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:

    <TextBlock>
      <Run Text="Temperature is "/>
      <Run Text="{Binding CelsiusTemp}"/>
      <Run Text="°C"/>  
    </TextBlock>
    
    <!-- displays: 0°C (32°F)-->
    <TextBlock>
      <Run Text="{Binding CelsiusTemp}"/>
      <Run Text="°C"/>
      <Run Text=" ("/>
      <Run Text="{Binding Fahrenheit}"/>
      <Run Text="°F)"/>
    </TextBlock>
    
    0 讨论(0)
提交回复
热议问题