benruehl / adonis-ui

Lightweight UI toolkit for WPF applications offering classic but enhanced windows visuals
https://benruehl.github.io/adonis-ui/
MIT License
1.71k stars 143 forks source link

Set color brushes using C# code. #98

Closed nitanmarcel closed 4 years ago

nitanmarcel commented 4 years ago

I have a question regarding using the color brushes in code.

I'm dynamically adding a textblock to a console I've made and I need to make use of the brushes to add different colors regarding if it's a success or an error. I know I could just drive into the code and copy the color value but I was wondering if there's a way to add the resource to the control by code.

I've tried using it like new TextBlock{Foreground=AdonisUI.Brush.ErrorColor} but it failed because it can't convert the resource to Color Brush.

benruehl commented 4 years ago

I think you are missing the DynamicResource part.

When using a brush in XAML you have something like this:

<TextBlock Foreground="{DynamicResource {x:Static adonisUi:Brushes.ErrorBrush}"/>

Remember that AdonisUI.Brushes.ErrorBrush is just a key to find the brush, not the brush itself.

Translating this to C# would result in something like this:

var tb = new TextBlock();
tb.SetResourceReference(Control.ForegroundProperty, AdonisUI.Brushes.ErrorBrush);

See here: https://stackoverflow.com/questions/1754615/how-to-assign-a-dynamic-resource-style-in-code

nitanmarcel commented 4 years ago

I think you are missing the DynamicResource part.

When using a brush in XAML you have something like this:

<TextBlock Foreground="{DynamicResource {x:Static adonisUi:Brushes.ErrorBrush}"/>

Remember that AdonisUI.Brushes.ErrorBrush is just a key to find the brush, not the brush itself.

Translating this to C# would result in something like this:

var tb = new TextBlock();
tb.SetResourceReference(Control.ForegroundProperty, AdonisUI.Brushes.ErrorBrush);

See here: https://stackoverflow.com/questions/1754615/how-to-assign-a-dynamic-resource-style-in-code

Thanks.