Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

path

wpf

People also ask

Is WPF and C# same?

C# is a programming language. WPF is a technology used to develop rich GUI applications using C# (or any other . NET language).

What is WPF in C# used for?

Windows Presentation Foundation (WPF) is a UI framework that creates desktop client applications. The WPF development platform supports a broad set of application development features, including an application model, resources, controls, graphics, layout, data binding, documents, and security.

Is WPF still relevant 2022?

“WPF would be dead in 2022 because Microsoft doesn't need to be promoting non-mobile and non-cloud technology. But WPF might be alive in that sense if it's the best solution for fulfilling specific customer needs today. Therefore, having a hefty desktop application needs to run on Windows 7 PCs with IE 8.

Is WPF used anymore?

WPF is still one of the most used app frameworks in use on Windows (right behind WinForms).


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.


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.


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;
    }