Programming Analytics

A feed of interesting tidbits from IT, software engineering, business intelligence, and videogaming.

While working on the UI of a WPF application, someone told me, “If you’re going to change the background color of the form, why not re-tint all the buttons to match it?”

So I thought I should write a tiny piece of code that takes as input a brush, lightens it by 50%, and assigns that to all controls of a certain type. Here’s how to do it:

private void RecolorChildren(DependencyObject dep, System.Windows.Media.Brush b)
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dep); i++) {
        DependencyObject child = VisualTreeHelper.GetChild(dep, i);
        if (child is System.Windows.Controls.Button) {
            System.Windows.Controls.Button button = child as System.Windows.Controls.Button;
            button.Background = b;
        } else if (child is System.Windows.Controls.ComboBox) {
            System.Windows.Controls.ComboBox cbx = child as System.Windows.Controls.ComboBox;
            cbx.Background = b;
        } else {
            RecolorChildren(child, b);
        }
    }
}

To tint a brush:

private static System.Windows.Media.Brush LightenBrush(System.Windows.Media.Brush b, int percent)
{
    SolidColorBrush scb = b as SolidColorBrush;
    System.Windows.Media.Color c2 = scb.Color;
    c2.B = (byte)(c2.B + ((double)(255 - c2.B) / 100.0 * percent));
    c2.G = (byte)(c2.G + ((double)(255 - c2.G) / 100.0 * percent));
    c2.R = (byte)(c2.R + ((double)(255 - c2.R) / 100.0 * percent));
    b = new SolidColorBrush(c2);
    return b;
}