Search code examples
c#canvasuwprectanglespathgeometry

Can Path.Data creation be simplified in code?


I have a Canvas in UWP, and need to draw Path on it in code-behind. I have it working, but it seems needlessly verbose, especially considering that I need to have four instances of it in a switch-case statement. I'm wondering if there's a way to simplify the code, or at least to consolidate it into a single line:

C#

Rect door = new Rect(left, top, width, height);
RectangleGeometry doorGeometry = new RectangleGeometry();
doorGeometry.Rect = door;
doorGroup.Children.Add(doorGeometry);
path.Data = doorGroup;

I tried putting it into a single line as below, but received several "No constructor with 1 elements" errors in IntelliSense. Is there a way to do this that simplifies/lessens the amount of code used?

GeometryGroup doorGroup = new GeometryGroup(new RectangleGeometry(new Rect(left, top, width, height);

Solution

  • You cannot write it in a simpler manner using just the built-in API. What you could do however is to write your own "builder" pattern-based class that could feature a Fluent API that would allow you to build up the path data "as a single statement".

    See this blog post as an example of a fluent builder.