经过反复试验和搜索,以下文章帮助了我:
Access ResourceDictionary items programmatically
如果每个 Xaml 矢量图像都包含在带有键的 ResourceDictionary 中(有关格式,请参阅下面我的第二篇文章)...
如果您的 Xaml 矢量图像文件都存储在您的项目中(构建操作:页面),您可以通过以下方式加载它们:
//Get the ResourceDictionary using the xaml filename:
ResourceDictionary dict = System.Windows.Application.LoadComponent(new Uri("/yourprojectname;component/youriconfolder/youriconfilename.xaml", System.UriKind.Relative)) as ResourceDictionary;
//Get the xaml as a DrawingImage out the ResourceDictionary
DrawingImage image = dict[dict.Keys.Cast<object>().ToList()[0]] as DrawingImage;
我可以返回图像并将其绑定到返回 iconfilename.xaml 的 viewmodel 属性。然后我使用带有上述代码的转换器来查找图标并将其作为 DrawingImage 返回。
或者您可以将其指定为图像的来源(请参阅下面我的第二篇文章)。
更新:2015.10.08 - Carl 似乎没有解决他帖子的“XAML 格式示例”部分。 XAML 看起来像这样:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DrawingImage x:Key="SomeUniqueKey">
<DrawingImage.Drawing>
<DrawingGroup>
...
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</ResourceDictionary>
那么你可以这样做:
DrawingImage image = dict["SomeUniqueKey"] as DrawingImage;
或者,如果您更喜欢直接使用Image,
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image x:Key="SomeUniqueImage">
<Image.Source>
<DrawingImage>
...
</DrawingImage>
</Image.Source>
</Image>
</ResourceDictionary>
还有:
Image someImage = dict["SomeUniqueImage"] as Image;