WPF - 使用XAML图标/矢量文件

时间:2015-06-23 14:42:37

标签: .net wpf xaml

我已经下载了http://modernuiicons.com/中的ModernUI图标,其中一种格式是xaml。

例如,appbar.printer.text.xaml文件包含:

    <?xml version="1.0" encoding="utf-8"?>
<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="appbar_printer_text" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
    <Path Width="44" Height="45" Canvas.Left="16" Canvas.Top="17" Stretch="Fill" Fill="#FF000000" Data="F1 M 25,27L 25,17L 51,17L 51,27L 47,27L 47,21L 29,21L 29,27L 25,27 Z M 16,28L 60,28L 60,51L 52,51L 52,46L 55,46L 55,33L 21,33L 21,46L 24,46L 24,51L 16,51L 16,28 Z M 25,39L 28,39L 28,52L 35,52L 35,59L 48,59L 48,39L 51,39L 51,62L 33,62L 25,54L 25,39 Z M 46,55L 38,55L 38,52L 46,52L 46,55 Z M 46,49L 30,49L 30,46L 46,46L 46,49 Z M 46,43L 30,43L 30,40L 46,40L 46,43 Z "/>
</Canvas>

有没有办法通过引用文件来使用它,还是我将内容复制并修改为资源字典?

1 个答案:

答案 0 :(得分:1)

有几种方法可以做你想做的事。

您可以将此xaml文件添加到resx资源文件。然后你可以用XamlReader加载它:

    void Load()
    {
        using (Stream s = GenerateStreamFromString(Properties.Resources.appbar_printer_text))
        {
            UIElement element = (UIElement)XamlReader.Load(s);
            // do what you want with this element
        }
    }

    Stream GenerateStreamFromString(string s)
    {
        MemoryStream stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(s);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }

如果您只想使用此文件中的Path作为Image的源,您可以将DrawingImage添加到ResourceDictionary:

<DrawingImage x:Key="appbar_printer_text">
    <DrawingImage.Drawing>
        <DrawingGroup>
            <DrawingGroup.Children>
                <GeometryDrawing Brush="#FF000000" Geometry="F1 M 25,27L 25,17L 51,17L 51,27L 47,27L 47,21L 29,21L 29,27L 25,27 Z M 16,28L 60,28L 60,51L 52,51L 52,46L 55,46L 55,33L 21,33L 21,46L 24,46L 24,51L 16,51L 16,28 Z M 25,39L 28,39L 28,52L 35,52L 35,59L 48,59L 48,39L 51,39L 51,62L 33,62L 25,54L 25,39 Z M 46,55L 38,55L 38,52L 46,52L 46,55 Z M 46,49L 30,49L 30,46L 46,46L 46,49 Z M 46,43L 30,43L 30,40L 46,40L 46,43 Z ">
                    <GeometryDrawing.Pen>
                        <Pen LineJoin="Round" Brush="#FF000000"/>
                    </GeometryDrawing.Pen>
                </GeometryDrawing>
            </DrawingGroup.Children>
        </DrawingGroup>
    </DrawingImage.Drawing>
</DrawingImage>

<Image Source="{StaticResources appbar_printer_text}" />

因此,您只需将数据从路径移动到几何。

类似的东西。