WPF C# Path: How to get from a string with Path Data to Geometry in Code (not in XAML)

C#WpfPath

C# Problem Overview


I want to generate a WPF Path object in Code.

In XAML I can do this:

 <Path Data="M 100,200 C 100,25 400,350 400,175 H 280">

How can I do the same in Code?

 Path path = new Path();
 Path.Data = "foo"; //This won't accept a string as path data.

Is there a class/Method available that converts the string with PathData to PathGeometry or similar?

Surely somehow the XAML gets parsed and the Data-string converted?

C# Solutions


Solution 1 - C#

var path = new Path();
path.Data = Geometry.Parse("M 100,200 C 100,25 400,350 400,175 H 280");

Path.Data is of type Geometry. Using Reflector JustDecompile (eff Red Gate), I looked at the definition of Geometry for its TypeConverterAttribute (which the xaml serializer uses to convert values of type string to Geometry). This pointed me to the GeometryConverter. Checking out the implementation, I saw that it uses Geometry.Parse to convert the string value of the path to a Geometry instance.

Solution 2 - C#

You could use the binding mechanism.

var b = new Binding
{
   Source = "M 100,200 C 100,25 400,350 400,175 H 280"
};
BindingOperations.SetBinding(path, Path.DataProperty, b);

I hope it helps you.

Solution 3 - C#

To make geometry from original text string You could use System.Windows.Media.FormattedText class with BuildGeometry() Method

 public  string Text2Path()
    {
        FormattedText formattedText = new System.Windows.Media.FormattedText("Any text you like",
            CultureInfo.GetCultureInfo("en-us"),
              FlowDirection.LeftToRight,
               new Typeface(
                    new FontFamily(),
                    FontStyles.Italic,
                    FontWeights.Bold,
                    FontStretches.Normal),
                    16, Brushes.Black);

        Geometry geometry = formattedText.BuildGeometry(new Point(0, 0));

        System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
        path.Data = geometry;

        string geometryAsString = geometry.GetFlattenedPathGeometry().ToString().Replace(",",".").Replace(";",",");
        return geometryAsString;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterdkView Question on Stackoverflow
Solution 1 - C#user1228View Answer on Stackoverflow
Solution 2 - C#dbvegaView Answer on Stackoverflow
Solution 3 - C#Alexander NikolaevView Answer on Stackoverflow