I'm trying to pass a @string/something
to a value converter so I can use it to format the output, so say I have a DateTime
value, I want to pass something like "Signup Date: {0}"
to the ValueConverter.
The problem is, the text above is translatable, so it came from the strings.xml
file of any given language. So far, I tried this:
<TextView
local:MvxBind="Text SignupDate, Converter=FriendlyDate, ConverterParameter=@string/release_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="5"
android:paddingTop="8dp"
style="@style/WhiteParagraphText" />
Note the ConverterParameter=@string/release_date
. How can I do it?
You can do this with a value converter that takes the string resource name as parameter, looks its id up in the resources and gets the value from the resources by this id.
public class FriendlyDateValueConverter : MvxValueConverter<DateTime, string>
{
protected override string Convert(DateTime value, Type targetType, object parameter, CultureInfo culture)
{
var param = parameter as string;
if (string.IsNullOrEmpty(param))
{
return string.Empty;
}
var globals = MvvmCross.Platform.Mvx.Resolve<IMvxAndroidGlobals>();
var res = globals.ApplicationContext.Resources;
var id = res.GetIdentifier(param, "string", globals.ApplicationContext.PackageName);
// id=0, if the resource could not be found -> add some error handling
var format = res.GetString(id);
return string.Format(format, value);
}
}
Usage
<TextView
local:MvxBind="Text SignupDate, Converter=FriendlyDate, ConverterParameter='release_date'"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="5"
android:paddingTop="8dp" />
Note: pass 'release_date'
instead of @string/release_date
as parameter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.