WPF绑定 - 为空字符串缺省值 [英] WPF Binding - Default value for empty string
问题描述
有没有设定一个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
似乎只踢当名称
为空,但不是当它被设置为的String.Empty
。
The FallbackValue
only seems to kick in when Name
is null, but not when it is set to String.Empty
.
推荐答案
我是IM pression下的<一个href=\"http://msdn.microsoft.com/en-GB/library/system.windows.data.bindingbase.fallbackvalue.aspx\">FallbackValue提供一个值时,绑定失败,<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.targetnullvalue.aspx\">TargetNullValue提供一个值时,势必值为null。
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绑定 - 为空字符串缺省值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!