Search code examples
c#wpfxamlwpf-stylegeometrydrawing

Defining style for GeometryDrawing


Please do not mark it as duplicate. The linked question is simply different from what I'm asking.

I need to set Pen and Brush properties for around 180+ GeometryDrawing objects. My first thought was to use a Style for it, but I learned that Style cannot target GeometryDrawing because it does not inherit from FrameworkElement. I then considered creating my own GeometryDrawing2 that inherits from GeometryDrawing and setting Pen and Brush in the constructor, but found that GeometryDrawing is sealed and can't be inherited.

What is the best way of achieving what I want other than copy-pasting the properties 180 times?

Edit

Here is my collection of drawings:

<ResourceDictionary>
  <DrawingImage x:Key="Drawing1">
    <DrawingImage.Drawing>
      <GeometryDrawing Geometry="..." />
    </DrawingImage.Drawing>
  </DrawingImage>

  <DrawingImage x:Key="Drawing2">
    <DrawingImage.Drawing>
      <GeometryDrawing Geometry="..." />
    </DrawingImage.Drawing>
  </DrawingImage>

  <!--180 more such drawings-->
</ResourceDictionary>

I need to set Brush and Pen for each of the GeometryDrawing objects to say Red and Black. The usual clean way in XAML is to do this through Style, but as I explained above, that doesn't work for GeometryDrawing. The only other way is to copy-paste Brush="{StaticResource MyBrush}" and Pen="{StaticResource MyPen}" to each of the 180+ GeometryDrawing objects. Or is there a faster (XAML-only) way?


Solution

  • Your question is still incomplete, lacking a good Minimal, Complete, and Verifiable code example to work with. But, based on the information you've provided so far, I would expect a template-based implementation to solve your problem. For example:

    <ResourceDictionary>
      <PathGeometry x:Key="geometry1">...</PathGeometry>
      <PathGeometry x:Key="geometry2">...</PathGeometry>
      <!-- etc. -->
    
      <DataTemplate DataType="{x:Type PathGeometry}">
        <DrawingImage>
          <DrawingImage.Drawing>
            <GeometryDrawing Geometry="{Binding}" Pen="..." Brush="..."/>
          </DrawingImage.Drawing>
        </DrawingImage>
      </DataTemplate>
    </ResourceDictionary>
    

    Then when you want to display one of those, just use a ContentControl or ContentPresenter. For example:

    <ContentControl Content="{StaticResource geometry1}"/>