How to bind a Localized string in the TargetNullValue attribute?

前端 未结 2 927
耶瑟儿~
耶瑟儿~ 2021-01-12 20:34

I have a Textblock which Text attribute is binding to a DateTime? type data, and I want to show something when the DateTime? data is null.
The code below works great.<

相关标签:
2条回答
  • 2021-01-12 21:06

    I don't see any way to do that with TargetNullValue. As a workaround, you can try using a converter:

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

    Then add it to the resources of your page:

    <phone:PhoneApplicationPage.Resources>
        <local:NullValueConverter x:Key="NullValueConverter" />
    </phone:PhoneApplicationPage.Resources>
    

    Finally, use it instead of TargetNullValue:

    <TextBlock Text="{Binding DueDate, Converter={StaticResource NullValueConverter}, ConverterParameter=bt_help_Title1}" />
    
    0 讨论(0)
  • 2021-01-12 21:28

    Since you can't have a binding inside another binding you will need to use a multi-binding.

    Something like:

    <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
    }
    
    0 讨论(0)
提交回复
热议问题