Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inherit from Brush, so I can add a Name property?

Tags:

c#

wpf

For example:

public class DesignerPatternBrush : Brush
{
    public string Name { get; set; }
}

I would like to define my own Brush class by adding a new property called Name, but there is a compiler error:

error CS0534: 'Brushes.DesignerPatternBrush' does not implement inherited abstract member 'System.Windows.Freezable.CreateInstanceCore()'

How can I add a Name property to a Brush type?

Note this related question: How do I implement a custom Brush in WPF? It answers the question of why it is not possible to literally inherit Brush. But is there some other way (e.g. using an attached property) to achieve the same effect I want?

like image 856
dongx Avatar asked Nov 20 '12 15:11

dongx


3 Answers

It means you need to implement all abstract methods that were inherited from Brush and its ancestors. In this case it's CreateInstanceCore() method of the Freezable class.

Why do you need a named brush? You can create a brush and store it into a ResourceDictionary (under a given key, which is basically a name) for your view/window/application - maybe you are looking for this solution.

More on that here: http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/03/creating-and-consuming-resource-dictionaries-in-wpf-and-silverlight.aspx

like image 88
Honza Brestan Avatar answered Nov 17 '22 04:11

Honza Brestan


As the compile error message says is Brush an abstract class --> you have to implement its abstract members

to let Visual Studio do all the work for you there exist a shortcut.

Select the Brush class and press Alt + Shift + F10 --> Enter the abstract class gets automatically implemented:

public class T : Brush
{

    protected override Freezable CreateInstanceCore()
    {
        throw new NotImplementedException();
    }
}

EDIT:

but this will not work with the Brush class. Visual Studio auto-implements all methods which are visible, but the Brush class defines some methods as internal abstract

i.e:

internal abstract int GetChannelCountCore();

As the Brush is defined in PresentationCore we will never be able to override the abstract method outside the assembly... --> impossible to inherit from the class

like image 2
fixagon Avatar answered Nov 17 '22 03:11

fixagon


When you inherit an abstract class you have some members that you need to Override. You will notice a little dropdown under Brush. If you press CTRL + . whilst your cursor is on Brush it will ask you to implement it, I press Enter afterCTRL + Space. When you implement it you will see this:

  protected override Freezable CreateInstanceCore()
  {
    throw new NotImplementedException();
  }
like image 1
LukeHennerley Avatar answered Nov 17 '22 05:11

LukeHennerley