空字符串的默认值

空字符串的默认值

本文介绍了WPF 绑定 - 空字符串的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a standard way to set a default or fallback value for a WPF binding if the bound string is empty?

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

FallbackValue 似乎只在 Name 为 null 时起作用,但当它设置为 String.Empty 时不会起作用.

The FallbackValue only seems to kick in when Name is null, but not when it is set to String.Empty.

推荐答案

我的印象是 FallbackValue 在绑定失败和 TargetNullValue 在绑定值为空时提供一个值.

I was under the impression that FallbackValue provides a value when the binding fails and TargetNullValue provides a value when the bound value is null.

要执行您想要的操作,您将需要一个转换器(可能带有参数)将空字符串转换为目标值,或者将逻辑放入您的视图模型中.

To do what you want you will either need a converter (possibly with a parameter) to convert an empty string to a target value, or put the logic in your view model.

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

I would probably go with a converter something like this (not tested).

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

这篇关于WPF 绑定 - 空字符串的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 20:20