We all know how String.Format and string interpolation works in C# so I'm not going into details how Converter_StringFormat works in XAML.
To give a few example, here's how string formatting works in C#
C#
string name = "Jayson";
string day = "Morning";
var formattedText = string.Format("Hello {0}, Good {1}!", name, day);
// output
// Hello Jayson, Good Morning!
or the string interpolation which is introduced in C# version 6
string name = "Jayson";
string day = "Morning";
var formattedText = $"Hello {name}, Good {day}!";
// output
// Hello Jayson, Good Morning!
So coming from our second example, this is where our Convert_StringFomat based at for XAML
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding ., Converter={StaticResource StringFormat}, ConverterParameter='• {Title}'}" FontAttributes="Bold" FontSize="15" />
<Span Text="{Binding ., Converter={StaticResource StringFormat}, ConverterParameter=' {Description} - Read more... by {Author} | {PubDate}'}" />
</FormattedString>
</Label.FormattedText>
</Label>
So to explain this a bit
"Binding ."
The "." is an object with properties "Title", "Description", "Author", and "PubDate"
This is how it looks like at run-time
So my 8 years issue is finally resolved. Starting from creating an app for Windows Phone 7 in year 2011
<TextBlock>
<Run Text="{Binding Title}" />
<LineBreak />
<Run Text="{Binding Description}" />
</TextBlock>
to WPF, UWP, and up until Xamarin<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding Title}" />
<Span Text=" " />
<Span Text="{Binding Description}" />
</FormattedString>
</Label.FormattedText>
</Label>
and I can now simplify my XAML code<Label Text="{Binding ., Converter={StaticResource StringFormat}, ConverterParamater'{Title} {Description}'}" />
One note though is, of course, this will not replace the way you format the font attributes. :)
So that's how it simply works. I hope this simple Converter can help you in someways
Here's a simple app I made that uses the Converter_StringFormat.
You can clone my code > Simple RSS Feed app in my github
https://github.com/Nullstr1ng/XamarinConverterStringFormat
Comments
Post a Comment