How to bind a localized string in the TargetNullValue attribute?

Do I have a Textblock whose Text attribute is bound to a DateTime? data type, and I want to show something when DateTime? data is zero.
The code below works fine.

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

But what about if I want to bind a localized string to a TargetNullValue?
The code below does not work :(
How?

  < TextBlock Text="{Binding DueDate, TargetNullValue={Binding LocalStrings.bt_help_Title1, Source={StaticResource LocalizedResources}} }"/> 
+6
source share
2 answers

I see no way to do this with TargetNullValue. As a workaround, you can try using the 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 your page resources:

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

Finally, use TargetNullValue instead:

 <TextBlock Text="{Binding DueDate, Converter={StaticResource NullValueConverter}, ConverterParameter=bt_help_Title1}" /> 
+3
source

Since you cannot have a binding inside another binding, you will need to use multi-binding.

Sort of:

 <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 } 
+1
source

Source: https://habr.com/ru/post/915566/


All Articles