如何在TargetNullValue属性中绑定本地化字符串?

6

我有一个TextBlock,其Text属性绑定了DateTime?类型的数据,当DateTime?数据为空时,我想显示一些内容。
下面的代码非常有效。

  < TextBlock Text="{Binding DueDate, TargetNullValue='wow,It's null'}"/>

但是如果我想将一个本地化字符串绑定到TargetNullValue,该怎么办?
下面的代码不起作用 :(
应该如何实现?

  < TextBlock Text="{Binding DueDate, TargetNullValue={Binding LocalStrings.bt_help_Title1, Source={StaticResource LocalizedResources}} }"/>
2个回答

4

我没有看到使用TargetNullValue实现这一点的方法。作为解决方法,您可以尝试使用转换器:

public class NullValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
        {
            return value;
        }

        var resourceName = (string)parameter;

        return AppResources.ResourceManager.GetString(resourceName);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后将其添加到您页面的资源中:
<phone:PhoneApplicationPage.Resources>
    <local:NullValueConverter x:Key="NullValueConverter" />
</phone:PhoneApplicationPage.Resources>

最后,使用它来替代TargetNullValue:
<TextBlock Text="{Binding DueDate, Converter={StaticResource NullValueConverter}, ConverterParameter=bt_help_Title1}" />

当添加所有这些内容时,构建时出现错误,{'local'是未声明的前缀。} :( - Albert Gao
这是因为你应该声明它。在你的页面的 phone:PhoneApplicationPage 节点上,使用其他xmlns一起加入:xmlns:local="clr-namespace:NamespaceOfYourProject" - Kevin Gosse

1

由于您无法在另一个绑定内部使用绑定,因此您需要使用多重绑定。

类似以下方式:

<Window.Resources>
    <local:NullConverter x:Key="NullConverter" />
</Window.Resources>

<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource NullConverter}">
            <Binding Path="DueDate"/>
            <!-- using a windows resx file for this demo -->
            <Binding Source="{x:Static local:LocalisedResources.ItsNull}" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

public class NullConverter : IMultiValueConverter
{
    #region Implementation of IMultiValueConverter

    public object Convert(object[] values, Type targetType, 
                          object parameter, CultureInfo culture)
    {
        if (values == null || values.Length != 2)
        {
            return string.Empty;
        }

        return (values[0] ?? values[1]).ToString();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, 
                                object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接