0

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);
E_net4
  • 27,810
  • 13
  • 101
  • 139
Keven M
  • 972
  • 17
  • 47

1 Answers1

1

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.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
  • Thanks for the blog post link, that was an interesting post. What I ended up doing (before seeing your answer) was to create a function that took in the left, top, width, and height parameters, and returns a GeometryGroup object. This way duplicate code is minimized, and the `switch` block is kept concise. I'm not sure in this case that the DoorPath warrants a whole class to itself, as would be needed for the fluent design, but for more important objects I could definitely see the appeal of the fluent design approach. – Keven M May 31 '19 at 12:47