You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF使用SharpVectors绑定SVG路径列表实现动态渲染的问题

解决方案

前置准备

首先在你的ViewModel中定义SVG路径的可观测集合,示例代码如下:

public class SvgViewModel : INotifyPropertyChanged
{
    // 你可以根据业务需求动态增删这个集合的元素
    public ObservableCollection<string> SvgPaths { get; set; } = new ObservableCollection<string>
    {
        "pack://application:,,,/你的程序集名称;component/Resources/0.svg",
        "pack://application:,,,/你的程序集名称;component/Resources/1.svg",
        "pack://application:,,,/你的程序集名称;component/Resources/2.svg",
        "pack://application:,,,/你的程序集名称;component/Resources/3.svg"
    };
}

两种实现方式可选

方式1:直接使用SvgImage标记扩展绑定(写法更简洁)

直接复用你固定加载时使用的svgc:SvgImage标记扩展,绑定路径即可,完整XAML示例:

<ItemsControl ItemsSource="{Binding SvgPaths}">
    <!-- 此处可自定义布局容器,比如替换为Grid、WrapPanel等 -->
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="3"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Stretch="Fill" Width="100" Height="100"
                   Source="{svgc:SvgImage Source={Binding}}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

方式2:适配你给出的SvgImageSource代码框架

直接给renderers:SvgImageSource的UriSource依赖属性绑定路径即可,修改后的代码如下:

<ItemsControl ItemsSource="{Binding SvgPaths}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Stretch="Fill" Width="100" Height="100">
                <Image.Source>
                    <renderers:SvgImageSource UriSource="{Binding}" />
                </Image.Source>
            </Image>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

注意事项

  • 确认XAML头部已引入SharpVectors对应的命名空间:
    xmlns:svgc="http://sharpvectors.codeplex.com/svgc/"
    xmlns:renderers="clr-namespace:SharpVectors.Rendering.Wpf;assembly=SharpVectors.Rendering.Wpf"
    
  • 路径格式说明:如果是项目内嵌资源,推荐使用上述pack URI格式,替换代码中的「你的程序集名称」为实际项目的程序集名即可;如果是本地磁盘文件直接传入绝对路径即可。

内容的提问来源于stack exchange,提问作者amplifier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:36:05