WPF绑定 - 空字符串的默认值

kro*_*mon 39 c# wpf xaml binding

如果绑定字符串为空,是否有标准方法为WPF绑定设置默认值或回退值?

<TextBlock Text="{Binding Name, FallbackValue='Unnamed'" />
Run Code Online (Sandbox Code Playgroud)

FallbackValue似乎只在踢Name空,但不是当它被设置为String.Empty.

ilt*_*rtz 69

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>
Run Code Online (Sandbox Code Playgroud)

  • +1表示不使用IValueConverter的不同方法. (5认同)
  • 这样做的方法很丑陋……对于这么简单的事情应该是 1 行。 (2认同)

Phi*_*hil 37

我认为FallbackValue在绑定失败时提供值,而TargetNullValue在绑定值为null时提供值.

要做你想做的事,你需要一个转换器(可能带参数)将空字符串转换为目标值,或者将逻辑放在视图模型中.

我可能会使用这样的转换器(未经测试).

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Viv*_*Viv 7

您应该为此创建一个转换器,它实现了 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在xaml中你只需要将转换器提供给绑定,(xxx只代表你的Window/ UserControl/ Style...绑定的位置)

<xxx.Resources>
<local:StringEmptyConverter x:Key="StringEmptyConverter" />
</xxx.Resources>
<TextBlock Text="{Binding Name, Converter={StaticResource StringEmptyConverter}, ConverterParameter='Placeholder Text'}" />
Run Code Online (Sandbox Code Playgroud)