【发布时间】:2021-05-27 20:05:29
【问题描述】:
我是 UWP 应用程序开发的新手,正在寻找一种将基于字符串的 SVG 绑定到 UWP(通用 Windows 平台)页面的方法。我想通过使用 UWP 页面的图像标签(XAML 布局)来展示基于字符串的 SVG。 SVG 将以 SVG 标记语言表示,例如:
dataBindedModel.svg = “<svg xmlns="http://www.w3.org/2000/svg"; width="500" height="500">
<circle cx="250" cy="250" r="210" fill="#fff" stroke="#000" stroke-width="8"/>
</svg>”;
为此,我需要在 XAML 中使用 {x:Bind},但不确定如何绑定它。 潜在的 XAML 代码如下:
<Image x:Name="MyImageView" Source="{x:Bind ...required area...”}>
更新:
我的 MainPage.xaml.cs:
public sealed partial class MainPage : Page
{
SVGModel dataBindedModel = new SVGModel();
public MainPage()
{
this.InitializeComponent();
dataBindedModel.SVGString = File.ReadAllText("test.xml");
this.DataContext = dataBindedModel;
}
}
public class SVGModel
{
public SVGModel() { }
public SVGModel(string svg)
{
SVGString = svg;
}
public string SVGString { get; set; }
}
我的MainPage.xaml:
<Grid>
<Grid.Resources>
<local:SVGImageConverter x:Key="MyConvert" />
</Grid.Resources>
<Image x:Name="MyImageView" Source="{x:Bind dataBindedModel.SVGString,Mode=OneWay,Converter={StaticResource MyConvert }}" />
</Grid>
我的test.xml:
<?xml version="1.0" encoding="utf-8" ?>
<svg width="500" height="500">
<circle cx="250" cy="250" r="210" fill="#fff" stroke="#000" stroke-width="8"/>
</svg>
【问题讨论】:
-
您所拥有的只是文本,而不是图像。将一些文本分配给
Image属性不会呈现它。<Image Source="Assets/mysvg.svg"/>有效,因为运行时将使用 SvgImageSource 在被识别为svg文件的路径和Image属性之间进行转换 -
SVG 是从哪里来的?一个文本文件?资源?在这种情况下,您只需将正确的路径传递给
Source。如果是运行时生成的字符串,可以绑定到 SvgImageSource 并使用SetSourceAsync 加载数据 -
@PanagiotisKanavos - 我的 SVG 是 XML 格式(test.xml 见上文)。我创建了一个 xml 文件,将我的 SVG xml 粘贴到其中。我正在 MainPage.xaml.cs 的构造函数中的 SVGModel 类的 SVGString 属性中读取这个 xml。 (见上文)但是为了运行代码而遇到了一些异常。
-
My SVG is in the XML format鉴于 SVG 是 XML,它什么也没说。您是否尝试过使用svg扩展名保存文件并按照链接文档显示的方式使用它?此外,那个test.xml文件在哪里?路径是相对的,这意味着应用程序将尝试在可执行文件夹中找到它,无论它在哪里。 Windows 应用程序是沙盒化的,这意味着当前目录不在您认为的位置,并且该应用程序也无法读取它想要的任何内容 -
@PanagiotisKanavos - 如何在 MainPage.xaml.cs 的 ctor 中直接使用 XML 设置 SVGString 属性。如果我尝试: dataBindedModel.SVGString = "";有什么想法吗?