David
David

Reputation: 307

How to extend the number of the brushes?

I want to extend the number of colors in the System.Windows.Media.Brushes class, so I can do binding with the string name of the new Brush.

Like: value="myRed".

I use C#, .NET 4.5.2, VS2015, Windows 7.

Upvotes: 2

Views: 96

Answers (1)

Mike Eason
Mike Eason

Reputation: 9713

This is not possible because the System.Drawing.Brushes class is sealed. This means it cannot be inherited from and therefore cannot be extended.

You are much better off creating a Resource Dictionary which contains your colours:

<ResourceDictionary ... >

    <!-- Declare your colours here. -->
    <SolidColorBrush x:Key="MyColour">#ffffff</SolidColorBrush>

</ResourceDictionary>

And then include that dictionary in your App.xaml:

<Application ... >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!-- You may need to include more than one resource dictionary. -->
                <ResourceDictionary Source="pack://application:,,,/Your.Project;component/Path/To/Dictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

You can get to those resources in the code-behind like this:

Brush myColour = (Brush)Application.Current.FindResource("MyColour");

In my opinion this is a much better way that extending the existing Brushes class because there's a clear divide between what is your code, and what is the .NET code. Not only that, having your colours in a resource dictionary promotes reuse across projects and the resources can be easily extended and become more adaptive to changing requirements.

You can find out more about resource dictionaries in the documentation.

Upvotes: 3

Related Questions