Dave F
Dave F

Reputation: 903

How to invert the colors of a WPF custom control

I'm creating a custom control for my WPF application, and I'd like to know how I can invert the colors of the control when it's clicked. I've gotten it to respond to mouse clicks, but when I try swapping the background and foreground brushes, only the background color changes. The control is a die control and I want the colors to be inverted when it's selected. I created the die faces by using a grid in the control template and placing ellipses with their fill brushes set to {TemplateBinding Foreground}. Any help would be greatly appreciated.

Upvotes: 1

Views: 5269

Answers (2)

Quartermeister
Quartermeister

Reputation: 59139

Put a trigger in your template that will replace the {TemplateBinding Foreground} with a "{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" and vice versa when your control is in the selected state. You can't use TemplateBinding from a setter, so you'll need to use a regular binding with a RelativeSource of TemplatedParent. Here is an example of a CheckBox with a TextBlock that inverts the colors when checked:

<CheckBox Foreground="Blue" Background="LightGreen">
    <ContentControl.Template>
        <ControlTemplate TargetType="CheckBox">
            <TextBlock Name="TextBlock"
                        Background="{TemplateBinding Background}"
                        Foreground="{TemplateBinding Foreground}"
                        Text="Text">
            </TextBlock>
            <ControlTemplate.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter TargetName="TextBlock" Property="Background"
Value="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}"/>
                    <Setter TargetName="TextBlock" Property="Foreground"
Value="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </ContentControl.Template>
</CheckBox>

Upvotes: 0

hkon
hkon

Reputation: 1045

You could use a pixel shader, look at e.g http://wpffx.codeplex.com/

it has an invertcolor which you can apply

Upvotes: 1

Related Questions