cindywmiao
cindywmiao

Reputation: 947

How to add a svg/xaml file in C# WPF windows just like image?

How to add a .svg file in a WPF window in C# as an image (,png || ,jpg)?

I use the code

<Image HorizontalAlignment="Left" Height="53" Margin="34,39,0,0"
           VerticalAlignment="Top" Width="71" 
           Source="Test.svg" Name="MyImage"/>

But I get an error:

Blend does not support format svg.

I found that I could change the .svg file into a .xaml file. But I still do not know how to add the xaml as an image.

Based on an answer, I changed my code like this:

<Window x:Class="NIA_UI_Demo_CSharp.ShareDocumentsWin"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:svgc="http://sharpvectors.codeplex.com/svgc/"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ShareDocumentsWin" Height="350" Width="569">

<ResourceDictionary>
    <Style x:Key="TheAwesomeXAMLimage" TargetType="ContentControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ContentControl">
                    my code
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

<Grid Margin="0,0,2,3">
    <ContentControl Style="{StaticResource TheAwesomeXAMLimage}"/>
</Grid>
</Window>

But I get an error:

Content is set more than once;

Upvotes: 11

Views: 32969

Answers (2)

BerndK
BerndK

Reputation: 1100

As far as I know you cannot include svg-files directly. Two options:

  1. use library that can handle svg-files in runtime: https://sharpvectors.codeplex.com/ (moved to https://github.com/ElinamLLC/SharpVectors)
  2. convert the svg to xaml and use them with native wpf objects (Path, Image..)

I prefer the second option, so I wrote a tool which can convert a single svg to xaml and can also batch convert a bunch of svg-files. The workflow is: just put the svg-file to your images-folder, call the batch-converter and find the images.xaml file (a resource-dictionary) updated with the new icons/images.

See https://github.com/BerndK/SvgToXaml

Upvotes: 24

Diego Frehner
Diego Frehner

Reputation: 2570

I was lucky that I have DevExpress available where you can use WpfSvgRenderer.CreateImageSource. Don't want to advertise here, but since it's a widely used library, probably some are happy to know.

Unfortunately text element inside the svg is not supported yet.

Upvotes: 0

Related Questions