Make conversion code reusable in Xamarin.Forms
In How to bind Xamarin.Forms Shapes Path Data to a string I expain how to convert an SVG path (stored in a resource file in this case) to the Data
property of a Path
view.
Now it would be useful to make the conversion code reusable across multiple views in the application.
example of SVG string data rendered in a Path
Here’s how to do it:
Step 1
Create a value converter
public class StringPathToGeometryConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string stringValue)
{
try
{
return (Geometry)new PathGeometryConverter()
.ConvertFromInvariantString(stringValue);
}
catch
{
return stringValue;
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Step 2
Instantiate the converter in the resource dictionary.
Register a namespace where the converter is located, for example:
...
xmlns:converters="clr-namespace:Musictheory.Converters"
...
Instantiate:
<ResourceDictionary>
<converters:StringPathToGeometryConverter
x:Key="StringPathToGeometryConverter" />
</ResourceDictionary>
Step 3
Reference the converter with the StaticResource
markup extension
<Path
Data="{Binding IconSvgPath,
Converter={StaticResource StringPathToGeometryConverter}}"
Stroke="White"
Fill="White"
StrokeThickness="1"
Aspect="Uniform"
VerticalOptions="Center"
HorizontalOptions="Center"/>
- Previous post: How to bind Xamarin.Forms Shapes Path Data to a string