views:

103

answers:

2

Hello,

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.

+1  A: 

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

it has an invertcolor which you can apply

hkon
A: 

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>
Quartermeister
Thank you. After I figured out that my Selected property needed to be a DependancyProperty, it worked perfectly.
Dave F