juFo
juFo

Reputation: 18587

Preferred way of showing images in XAML from resource

I have a .xaml file with a ResourceDictionary containing all my custom icons.

e.g.:

<Canvas x:Key="imgFoo" Width="16" Height="16">
    <Path Fill="#FFFF0000" StrokeThickness="3" Stroke="#FFFF0000" StrokeMiterLimit="4" StrokeLineJoin="Round" StrokeStartLineCap="Round" StrokeEndLineCap="Round">
        <Path.Data>
            <PathGeometry Figures="M 2.0722892 ..... 4.0457831" FillRule="NonZero"/>
        </Path.Data>
    </Path>
</Canvas>

Now the question: what is the best way to use this resource in xaml?

Is it for example like this:

<TabItem>
    <TabItem.Header>
        <StackPanel Orientation="Horizontal">
            <ContentControl Content="{StaticResource imgFoo}" />
            <TextBlock Text="Foo" />
        </StackPanel>
    </TabItem.Header>

Is using a ContentControl the correct way of using and displaying this resource?

Update: and what about this method of using a drawingbrush and a border. Is this a good way?

<DrawingBrush x:Key="imgF00">
    <DrawingBrush.Drawing>
        <GeometryDrawing>
            <GeometryDrawing.Pen>
                <Pen Thickness="3" MiterLimit="4" LineJoin="Round" StartLineCap="Round" EndLineCap="Round" Brush="#FFFF0000" />
            </GeometryDrawing.Pen>
            <GeometryDrawing.Geometry>
                <PathGeometry Figures="M 2.0722892 ... 4.0457831" FillRule="NonZero" />
            </GeometryDrawing.Geometry>
        </GeometryDrawing>
    </DrawingBrush.Drawing>
</DrawingBrush>

showing it via a border:

 <TabItem>
    <TabItem.Header>
        <StackPanel Orientation="Horizontal">
            <Border Background="{StaticResource imgFail2}" Width="16" Height="16" />
            <TextBlock Text="Failure" />
        </StackPanel>
    </TabItem.Header>

Upvotes: 1

Views: 1706

Answers (1)

Clemens
Clemens

Reputation: 128146

Instead of using UI elements (like Canvas an Path) as icon resources, you may use DrawingBrush objects like this:

<DrawingBrush x:Key="imgFoo" ViewboxUnits="Absolute" Viewbox="0,0,16,16">
    <DrawingBrush.Drawing>
        <GeometryDrawing Brush="#FFFF0000">
            <GeometryDrawing.Pen>
                <Pen Thickness="3" Brush="#FFFF0000" MiterLimit="4" LineJoin="Round" StartLineCap="Round" EndLineCap="Round"/>
            </GeometryDrawing.Pen>
            <GeometryDrawing.Geometry>
                <PathGeometry Figures="..." FillRule="NonZero"/>
            </GeometryDrawing.Geometry>
        </GeometryDrawing>
    </DrawingBrush.Drawing>
</DrawingBrush>

You may now use such a Brush for e.g. the Fill property of a Rectangle:

<TabItem.Header>
    <StackPanel Orientation="Horizontal">
        <Rectangle Fill="{StaticResource imgFoo}" Width="16" Height="16"/>
        <TextBlock Text="Foo" />
    </StackPanel>
</TabItem.Header>

Upvotes: 2

Related Questions