How to get color from HEX code in C# (WPF and WinForms)?
Hello, colleagues! I'm a beginner C# developer, writing a small WPF application for viewing images. I need the user to be able to enter a background color as a HEX code (for example, #FFAABB or just AABBCC) in a text field, and the program should change the window background.
The problem is that I can't find a standard way to convert a string like "#FF4500" into a Color or Brush object in .NET. I tried googling, but I keep coming across various makeshift solutions — some people parse the string manually, others use ColorTranslator, but it doesn't work in WPF. In WinForms there seems to be ColorTranslator.FromHtml, but I'm writing for WPF.
Here's my current code that doesn't work:
```csharp
string hexColor = "#FF5733";
// Trying to get the color
Color color = Color.FromRgb(0xFF, 0x57, 0x33); // Only works for static values
No answers yet.
Log in to leave an answer
Blogs