TAGS :Viewed: 6 - Published at: a few seconds ago

[ How to store a Brush in a User Setting ]

I'm pretty new to C# and WPF and I just found out about reading from and storing to User/Application settings. Now I want to store a Brush of a TextBox but I can't find a type for that.

I tried using SystemDrawing.Color to store at least the color, but doing so clashes with all the references to System.Windows.Media I have (such as Brush and FontFamily) and I'd rather not go there.

So got any suggestions for a greenhorn like me?

Answer 1

You can get the HEX value from the Color

string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", [Color].A, [Color].R, [Color].G, [Color].B);

Store the HEX string into user settings. Then convert back the string to SolidColorBrush:

SolidColorBrush solidColorBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#hexhex"));

Answer 2

This is how I went about it thanks to this related answer: I just implemented a new Class to convert between the different types.

using MediaColor = System.Windows.Media.Color;
using DrawingColor = System.Drawing.Color;

public static class ColorConverter

    public static MediaColor ToMediaColor(this DrawingColor color)
        return MediaColor.FromArgb(color.A, color.R, color.G, color.B);

    public static DrawingColor ToDrawingColor(this MediaColor color)
        return DrawingColor.FromArgb(color.A, color.R, color.G, color.B);


And in my app, I just call a function to create Brushes out of the colors on startup:

MainWindow m = mainWindow;

m.brushWindowBg = new SolidColorBrush(classes.ColorConverter.ToMediaColor(Settings.Default.brushWindowBg));
m.brushCanvasFg = new SolidColorBrush(classes.ColorConverter.ToMediaColor(Settings.Default.brushCanvasFg));
m.brushCanvasBg = new SolidColorBrush(classes.ColorConverter.ToMediaColor(Settings.Default.brushCanvasBg));

On Exit, I convert the Brush colors back to Drawing.Color:

MainWindow m = mainWindow;

Settings.Default.brushWindowBg = classes.ColorConverter.ToDrawingColor(m.brushWindowBg.Color);
Settings.Default.brushCanvasFg = classes.ColorConverter.ToDrawingColor(m.brushCanvasFg.Color);
Settings.Default.brushCanvasBg = classes.ColorConverter.ToDrawingColor(m.brushCanvasBg.Color);