动态绑定xaml矢量图像
我正在寻找一种在代码中动态绑定xaml图像的方法。动态绑定xaml矢量图像
在线有很多示例可以显示如何在窗口的xaml中绑定png或xaml图像,或者在代码中加载png文件。
但是我没有发现xaml文件的build action = page的例子。 XmlReader无法处理它们,因为它们被编译为baml。 (新的Uri(“... filename.baml”)将明显加载baml,但我加载了什么样的图像类?BitmapImage(new Uri(“... filename.baml”)会。似乎没有工作,可能是因为它不是一个位图
在此先感谢
大量的试验和错误和搜索后,下面的文章让我对我的方式: 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。然后,我使用具有上述代码的转换器来查找图标并将其作为DrawingImage返回。 或者你可以指定它作为图像的来源(见我的第二篇文章下面)。
UPDATE:2015.10.08 - 看起来卡尔没有考虑到他的文章的“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;
此外,如果你的图像存储了XAML矢量文件中这样的格式:
您可以通过以下方式加载单独的XAML矢量图像(它可能是最好的防止字典被多次添加,如果你像我一样是通过一个OpenFileDialog)加载它:
C#:
串fullPathAndFileName = “C:\ Image_Name.xaml”; ResourceDictionary dict = new ResourceDictionary(); dict.Source = new Uri(fullPathAndFileName); Application.Current.Resources.MergedDictionaries。加入(字典);
DrawingImage image = dict [dict.Keys.Cast()。ToList()[0]] as DrawingImage; myImage.Source = image;
XML:
图像高度= “200” WIDTH = “200” X:名称= “MYIMAGE”