How do I implement a custom Brush in WPF?

MojoFilter picture MojoFilter · Apr 27, 2009 · Viewed 10.3k times · Source

Where can I find out enough info about how Brushes work to implement my own System.Windows.Media.Brush? I can handle all of the freezable baggage, but it's not really obvious what I need to override to get it to work.


Yeah, so I didn't mean that I want to use a predefined brush. I want to extend System.Windows.Media.Brush, which is an abstract class. This is all purely for my own edification. I'm not even sure what kind of brush I could make. I was just trying to learn how brushes work. As in:

public AwesomeBrush : Brush
{

    protected override Freezable CreateInstanceCore()
    {
        return new AwesomeBrush();
    }

    ... // concrete brush stuff

}

Answer

Mikko Rantanen picture Mikko Rantanen · Apr 27, 2009

I had a quick look at the existing brushes using the Reflector. It seems like their implementation is pretty closed up and depends on lots of internal plumbing. While it might be possible to implement your own brush it seems like it is not a supported option. It could even be that the WPF controls are tied tightly to the existing brushes and will not work with a custom one.

Most likely the best way to achieve something resembling custom brushes is to use the DrawingBrush with some complex drawing logic. You can compose drawing brush from complex shapes using other brushes so this should let you achieve the required goal.

Update after edit

As this is for education, you might be best off downloading the Reflector and using that to see how the brushes work. They are not meant to be self-implemented and since they rely on some internal classes to which programmers do not have access normally it will be quite hard to do so.

Though what makes it interesting is that the Brush documentation does have a remark for inheritors to guide in the correct way to inherit from the Brush.

More updates

When poking around I found a quite neat way to achieve something similar on a chinese blog. The trick there is to use a markup extension so it just looks like a brush. In reality it creates a new image brush based on its attributes. Seems he came to the same conclusion that there are some internal classes which prevent the easy implementation.