programing

WPF 바인딩 - 빈 문자열 기본값

cafebook 2023. 4. 23. 11:27
반응형

WPF 바인딩 - 빈 문자열 기본값

바인드 문자열이 비어 있는 경우 WPF 바인딩 기본값 또는 폴백 값을 설정하는 표준 방법이 있습니까?

<TextBlock Text="{Binding Name, FallbackValue='Unnamed'" />

FallbackValue할 때만 효과가 있는 것 같다Namenull입니다만, 로 설정되어 있는 경우는 없습니다.String.Empty.

DataTrigger내가 이렇게 하는 거야

<TextBox>
  <TextBox.Style>
        <Style TargetType="{x:Type TextBox}"  BasedOn="{StaticResource ReadOnlyTextBox}">
            <Setter Property="Text" Value="{Binding Name}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Name.Length, FallbackValue=0, TargetNullValue=0}" Value="0">
                    <Setter Property="Text" Value="{x:Static local:ApplicationLabels.NoValueMessage}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

바인딩이 실패하면 FallbackValue가 값을 제공하고 바인딩된 값이 null이면 TargetNullValue가 값을 제공하는 것으로 생각했습니다.

원하는 작업을 수행하려면 빈 문자열을 대상 값으로 변환하는 변환기(가능한 경우 매개 변수 포함)가 필요하거나 뷰 모델에 로직을 넣어야 합니다.

아마 이런 컨버터(테스트되지 않은 것)를 사용할 것입니다.

public class EmptyStringConverter : MarkupExtension, IValueConverter
{  
    public object Convert(object value, Type targetType, 
                          object parameter, CultureInfo culture)
    {
        return string.IsNullOrEmpty(value as string) ? parameter : value;
    }

    public object ConvertBack(object value, Type targetType, 
                              object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

이를 위한 컨버터를 생성해야 합니다.이 컨버터는IValueConverter

public class StringEmptyConverter : IValueConverter {

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
      return string.IsNullOrEmpty((string)value) ? parameter : value;
    }

public object ConvertBack(
      object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
      throw new NotSupportedException();
    }

}

그런 다음 xaml에서는 변환기를 바인딩에 제공합니다.xxx를 대표합니다.Window/UserControl/Style... 바인딩 위치)

<xxx.Resources>
<local:StringEmptyConverter x:Key="StringEmptyConverter" />
</xxx.Resources>
<TextBlock Text="{Binding Name, Converter={StaticResource StringEmptyConverter}, ConverterParameter='Placeholder Text'}" />

변환기를 사용하여 해당 검증을 수행할 수 있습니다.

Binding="{Binding Path=Name, Converter={StaticResource nameToOtherNameConverter}}"

변환기 안에

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!string.IsNullOrEmpty(value.ToString()))
        { /*do something and return your new value*/ }

언급URL : https://stackoverflow.com/questions/15567588/wpf-binding-default-value-for-empty-string

반응형