Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use image as WPF Button icon mask?

Tags:

icons

wpf

I'd like to know if it's possible to do the following:

  • create a black and white image, say of a dog
  • add the image to a button as a mask
  • change the style using (data) triggers, e.g. disabled - the dog is grey, "loading" - the dog is red, "ready" the dog is yellow, etc.

Basically I want to create button icons using pixels but be able to set the color at runtime depending on triggers. Something like this:

dog buttons

like image 732
DaveO Avatar asked Apr 26 '11 11:04

DaveO


1 Answers

After 2 hours of googling here's the answer

<Window x:Class="IconTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!-- button style -->
        <Style x:Key="ToolButton" TargetType="Button">
            <Setter Property="OverridesDefaultStyle" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Width="16" Height="16" Background="#ffbbbbbb">
                            <Rectangle Name="rect" Fill="Black" OpacityMask="{TemplateBinding Content}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="rect" Property="Fill" Value="Green" />
                            </Trigger>
                            <Trigger Property="IsPressed" Value="True">
                                <Setter TargetName="rect" Property="Fill" Value="Yellow" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    </Window.Resources>
    <Grid>
        <Button Width="16" Height="16" Style="{StaticResource ToolButton}">
            <ImageBrush ImageSource="/test.png"/>
        </Button>
    </Grid>
</Window>
like image 178
DaveO Avatar answered Sep 22 '22 19:09

DaveO