Programing

StringFormat을 사용하여 WPF XAML 바인딩에 문자열을 추가하십시오.

lottogame 2020. 7. 22. 21:30
반응형

StringFormat을 사용하여 WPF XAML 바인딩에 문자열을 추가하십시오.


정수 값 (이 경우 섭씨 온도)에 단방향 바인딩이있는 TextBlock을 포함하는 WPF 4 응용 프로그램이 있습니다. XAML은 다음과 같습니다.

<TextBlock x:Name="textBlockTemperature">
        <Run Text="{Binding CelsiusTemp, Mode=OneWay}"/></TextBlock>

이것은 실제 온도 값을 표시하는 데는 효과적이지만 숫자 대신 ° C (30 대신 30 ° C)를 포함하도록이 값을 형식화하고 싶습니다. StringFormat에 대해 읽었으며 다음과 같은 몇 가지 일반적인 예를 보았습니다.

// format the bound value as a currency
<TextBlock Text="{Binding Amount, StringFormat={}{0:C}}" />

// preface the bound value with a string and format it as a currency
<TextBlock Text="{Binding Amount, StringFormat=Amount: {0:C}}"/>

불행히도, 내가 본 예제 중 아무것도 바운드 값에 문자열을 추가하지 않았습니다. 나는 그것이 간단한 것이 틀림 없다고 확신하지만 그것을 찾는 운이 없다. 누구든지 저에게 그 방법을 설명 할 수 있습니까?


첫 번째 예는 실제로 필요한 것입니다.

<TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />

다음은 문자열 중간에 바인딩 또는 여러 바인딩이있는 경우 가독성을 높이는 대안입니다.

<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>

바인딩에서 StringFormat을 사용하는 것은 "text"속성에서만 작동하는 것 같습니다. Label.Content에 이것을 사용하면 작동하지 않습니다


xaml에서

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

에서 ViewModel값을 설정이 방법으로도 작동합니다 :

 public string CelsiusTemp
        {
            get { return string.Format("{0}°C", _CelsiusTemp); }
            set
            {
                value = value.Replace("°C", "");
              _CelsiusTemp = value;
            }
        }

참고 URL : https://stackoverflow.com/questions/19278515/use-stringformat-to-add-a-string-to-a-wpf-xaml-binding

반응형