Changing image basing on color, wpf

1.5k views Asked by At

I've got the following scenario. Somewhere there is a DynamicResource with color. This color determines background of windows and basing on that color I want to choose right icons to display (bright or dark).

I imagine the following scenario:

  • The color changes, triggering a change in my class
  • My class checks, which icon set should be chosen
  • It forces all users of these icons to reload them.

I guess, that this should be doable using WPF mechanisms. The problem is, that I don't quite know, how to build architecture, which will do such processing.

  1. Capturing color change. I guess, that I can write a class with a DependencyProperty called, say, BackgroundColor and then attach that color through a DynamicResource. This way I can capture the color change using the PropertyChangedCallback.
  2. Internal processing is easy.
  3. I have to expose my icons, such that they will be attachable through the DynamicResource mechanism. How? By some kind of collection? Each one by its own DependencyProperty?
  4. I have to notify all users of these icons, that they have changed. How? By IObservableCollection? Calling NotifyPropertyChanged on each property representing an icon? Maybe in some other way?

If there's a simpler way to achieve the goal I presented, I'll gladly hear it :)

1

There are 1 answers

2
Sheridan On BEST ANSWER

You could just create a light and a dark WPF Theme and then switch between them dependant on the colour currently set as the background colour. Using this method, WPF will take care of all of the icon updates.

If you want to create your own system, you can use the DependencyProperty system to help you:

Background colour is changed:

You can simply add a PropertyChangedCallback handler to the current Background property:

static YourControl()
{
    Control.BackgroundProperty.OverrideMetadata(typeof(YourControl), 
        new PropertyMetadata(Brushes.White, OnBackgroundChanged));
}

private static void OnBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // The Background property value changed
}

Exposing Icons and notifying the UI:

You can create a class that holds a string property to data bind to each Image.Source property in the following format:

"\ApplicationName;component/ImageFolderName/ImageName.FileExtension"

As long as this class implements the INotifyPropertyChanged interface, then all you need to do is to change these string values and the UI will automatically update with the new icons or images.