Search code examples
wpfcolor-schemedynamicresourceancestor

Setting resource styles dynamically through binding in WPF


I am trying to make the color scheme of my application dynamic so that I can have a color value in a property(hopefully coming from the database) that determines the color scheme of my application.

I have a Resources.xaml file where I set my colors and styles for the application, which I then use throughout all my controls and windows. I would like to bind the Color of a SolidColorBrush in the resources file to a property in my ViewModel(s) so that this color can change based on the current application value. Here is what I have so far, but it isn't working so I must be missing something.

Code in the Resources.xaml file:

<SolidColorBrush x:Key="ApplicationMainBackgroundBrush" Color="{Binding Path=MainApplicationColor, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ApplicationArchitecture:ViewModelBase}, Mode=FindAncestor}, FallbackValue=CornflowerBlue}"/>  

Code in the MainWindow.xaml file:

<Grid Grid.Row="0" x:Name="gridControl" Background="{DynamicResource ApplicationMainBackgroundBrush}">

The DataContext of my MainWindow.xaml is a class called ApplicationViewModel, which inherits from ViewModelBase, which has a property "MainApplicationColor" returning the string "Teal" to change the color of that SolidColorBrush from it's FallbackValue. I'm hard coding the color for now, but this is where I would like to get my value from the database in the future. The color is currently not changing, so I'm assuming there is something wrong in my binding source as it is clearly not working like I think it should.

Thanks,

Klara


Solution

  • The problem seems to be your SolidColorBrush.Color property's Binding.

    1. There the ancestor type should be ApplicationArchitecture:MainWindow and not ApplicationArchitecture:ViewModelBase.

    2. The Path should include the DataContext in it.

    Like this....

      <SolidColorBrush x:Key="ApplicationMainBackgroundBrush"
                       Color="{Binding Path=DataContext.MainApplicationColor,
                                  RelativeSource={RelativeSource FindAncestor, 
                                      AncestorType={x:Type ApplicationArchitecture:MainWindow},
                                          Mode=FindAncestor},
                                              FallbackValue=CornflowerBlue}"/>
    

    Let me know if this helps.