06 July 2014

Using Modern UI Icons

In my research, I stumbled across the excellent Modern UI Icons.

I downloaded them and put the XAML files in a test application. Eventually, I got the the point of adding them to a view. That's when the problems started. The XAML files can't be used as sources for an Image. And here I was thinking it was an image format like SVG.

Eventually, I was able to setup a useful style for a ContentControl. This can be resized and the color-changed as well.

Here is what I ended up with:

    <Style TargetType="ContentControl" x:Key="icon">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ContentControl">
                    <Viewbox Height="{TemplateBinding Height}" Stretch="Uniform">
                        <ContentPresenter />
                    </Viewbox>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Canvas x:Shared="False" x:Key="icon-calculator"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="appbar_calculator" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
        <Path Width="32" Height="42" Canvas.Left="22" Canvas.Top="17" Stretch="Fill" Fill="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}, Path=Foreground}" Data="..."/>
    </Canvas>

I left the data out of this example for brevity. The Path data is in the XAML files for the modern UI icon. The yellow stuff is what I had to add.

1) Setting x:Shared to False is necessary otherwise WPF will only display the icon once, no matter how many times you reference it.
2) Settings x:Key is also necessary so you can reference it.
3) The Fill binding allows me to change the brush color

So here's how to use the icon.

<ContentControl Style="{StaticResource icon}" Content="{StaticResource icon-calculator}" Height="32" Foreground="Black"/>

I could probably shorten this with a custom control. However, the only thing it would save is the Style declaration. So I haven't bothered yet.

No comments: