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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15567588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:11:45  来源:igfitidea点击:

WPF Binding - Default value for empty string

c#wpfxamlbinding

提问by kroimon

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

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

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

The FallbackValueonly seems to kick in when Nameis null, but not when it is set to String.Empty.

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

采纳答案by Phil

I was under the impression that FallbackValueprovides a value when the binding fails and TargetNullValueprovides a value when the bound value is null.

我的印象是,当绑定失败时FallbackValue提供一个值,而当绑定值为 null 时TargetNullValue提供一个值。

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

回答by Santux

You could use a converter and do the respective validation on it.

您可以使用转换器并对其进行相应的验证。

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

and in your converter

并在您的转换器中

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

回答by Viv

You should create a converter for this, which implements IValueConverter

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

}

Then in xaml you'd just provide the converter to the binding, (xxxjust represents your Window/ UserControl/ Style... where the binding is)

然后在XAML中你只需要提供转换器的结合,(xxx只是代表你Window/ UserControl/ Style...这里的绑定)

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

回答by iltzortz

DataTriggeris the way i do it like this:

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>