IT Share you

레이블 콘텐츠의 WPF StringFormat

shareyou 2020. 11. 9. 21:35
반응형

레이블 콘텐츠의 WPF StringFormat


레이블에 바인딩 된 속성이있는 Amount is X위치 로 문자열 바인딩의 형식을 지정하고 싶습니다 X.

많은 예를 보았지만 다음은 작동하지 않습니다.

<Label Content="{Binding Path=MaxLevelofInvestment, 
   StringFormat='Amount is {0}'}" />

나는 또한 다음 조합을 시도했습니다.

StringFormat=Amount is {0}
StringFormat='Amount is {}{0}'
StringFormat='Amount is \{0\}'

바인딩 속성의 데이터 유형을 int, stringdouble. 아무것도 작동하지 않는 것 같습니다. 이것은 매우 일반적인 사용 사례이지만 지원되지 않는 것 같습니다.


이것이 작동하지 않는 이유는 Label.Content속성이 type Object이고 Binding.StringFormattype 속성에 바인딩 할 때만 사용되기 때문 String입니다.

무슨 일이 일어나고 있는지 :

  1. Binding당신의 권투 MaxLevelOfInvestment값을하고 그것을 수납 Label.Content박스형 진수 값으로 속성을.
  2. Label 컨트롤에는 ContentPresenter.
  3. ContentTemplate가 설정되지 않았 으므로 유형 ContentPresenter에 대해 DataTemplate정의 된 것을 찾습니다 Decimal. 아무것도 찾지 못하면 기본 템플릿을 사용합니다.
  4. 에서 사용하는 기본 템플릿 ContentPresenter은 레이블의 ContentStringFormat속성 을 사용하여 문자열을 표시 합니다.

두 가지 솔루션이 가능합니다.

  • Binding.StringFormat 대신 Label.ContentStringFormat을 사용하거나
  • Label.Content 대신 TextBlock.Text와 같은 String 속성을 사용합니다.

Label.ContentStringFormat을 사용하는 방법은 다음과 같습니다.

<Label Content="{Binding Path=MaxLevelofInvestment}" ContentStringFormat="Amount is {0}" />

TextBlock을 사용하는 방법은 다음과 같습니다.

<TextBlock Text="{Binding Path=MaxLevelofInvestment, StringFormat='Amount is {0}'}" />

참고 : 나는 위의 설명에서 하나의 디테일을 생략 단순화하기 위해는 다음 ContentPresenter실제로는 자신의 사용 TemplateStringFormat이러한 자동으로 템플릿 바인딩에있는 속성을하지만,로드시 ContentTemplateContentStringFormat의 속성 Label은 if로 보인다 때문에, ContentPresenter실제로 사용 Label의 특성을 .


보편적 인 StringFormatConverter : IValueConverter. 형식 문자열을 ConverterParameter.

Label Content="{Binding Amount, Converter={...myConverter}, ConverterParameter='Amount is {0}'"

또한 StringFormatMultiConverter : IMultiValueConverter형식 문자열에 둘 이상의 개체가 필요할 때 만들 수 있습니다 (예 : Completed {0} tasks out of {1}.


방금 확인한 결과 어떤 이유로 Label에서 작동하지 않습니다. 아마도 Content 속성에 대해 ContentPresenter를 내부적으로 사용하기 때문일 것입니다. 대신 TextBlock을 사용할 수 있으며 작동합니다. 스타일, 동작 등을 상속해야하는 경우 아래의 TextBlock 발췌 부분을 Label의 내용에 넣을 수도 있습니다.

<TextBlock Text="{Binding Path=MaxLevelofInvestment, StringFormat='Amount is \{0\}'} />

변환기를 사용해보십시오 ....

<myconverters:MyConverter x:Key="MyConverter"/>


<Label Content="{Binding Path=MaxLevelofInvestment, Converter={StaticResource MyConverter"} />


public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return String.Format("Amount is {0}", value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

아마도 이것이 도움이 될 것입니다 ...

XAML에 코드 포함

참고 URL : https://stackoverflow.com/questions/4206612/wpf-stringformat-on-label-content

반응형