반응형
WPF 바인딩 - 빈 문자열 기본값
바인드 문자열이 비어 있는 경우 WPF 바인딩 기본값 또는 폴백 값을 설정하는 표준 방법이 있습니까?
<TextBlock Text="{Binding Name, FallbackValue='Unnamed'" />
그FallbackValue
할 때만 효과가 있는 것 같다Name
null입니다만, 로 설정되어 있는 경우는 없습니다.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
반응형
'programing' 카테고리의 다른 글
ASP를 강제하는 방법이 있나요?일반 텍스트를 반환하려면 NET Web API를 선택하십시오. (0) | 2023.04.23 |
---|---|
쿼리 문자열에 서명하기 (0) | 2023.04.23 |
Windows 탐색기에서 PowerShell을 시작하는 방법 (0) | 2023.04.23 |
WPF 리소스에 정수 값이 있습니까? (0) | 2023.04.23 |
UITextView에서의 마진/패딩 손실 방법 (0) | 2023.04.23 |