2010-05-10 77 views
1

我正在尋找一種在代碼中動態綁定xaml圖像的方法。動態綁定xaml矢量圖像

在線有很多示例可以顯示如何在窗口的xaml中綁定png或xaml圖像,或者在代碼中加載png文件。

但是我沒有發現xaml文件的build action = page的例子。 XmlReader無法處理它們,因爲它們被編譯爲baml。 (新的Uri(「... filename.baml」)將明顯加載baml,但我加載了什麼樣的圖像類?BitmapImage(new Uri(「... filename.baml」)會。似乎沒有工作,可能是因爲它不是一個位圖

在此先感謝

回答

0

大量的試驗和錯誤和搜索後,下面的文章讓我對我的方式: 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; 
1

此外,如果你的圖像存儲了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」