0

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?

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
Phil Strahl
  • 165
  • 1
  • 1
  • 8
  • Check [this](http://stackoverflow.com/questions/17833315/bind-drawing-color-from-settings-with-style-in-xaml/17834421#1783442) answer. It may help you. – dkozl Jan 10 '16 at 21:16

2 Answers2

3

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"));
fillobotto
  • 3,698
  • 5
  • 34
  • 58
0

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));
//etc.

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);
//etc.
Community
  • 1
  • 1
Phil Strahl
  • 165
  • 1
  • 1
  • 8