2009-07-10 70 views
15

我希望能夠將矢量圖形(最好在XAML中定義)用作圖像控件的來源,就像我目前可以像PNG一樣使用光柵圖像。這樣,我可以很容易地混合和位圖和矢量圖像之間的匹配,就像這樣:使用XAML文件作爲矢量圖片源

<StackPanel> 
    <Image Source="Images/Namespace.png"/> 
    <Image Source="Images/Module.xaml"/> 
</StackPanel> 

Module.xaml將最有可能<DrawingImage>作爲它的根元素,而不是<UserControl>

其實,我真的去爲的就是這個,所以我的視圖模型可以根據自己的判斷選擇一個柵格或矢量圖像:

<Image Source="{Binding ImageUri}"/> 

這可能嗎? Image.Source可以從給定的URI加載XAML類嗎?或者它只能加載位圖資源?

+4

讓我懷疑......爲什麼在WPF/Silverlight中使用XAML圖像會如此困難,或者本機不支持......考慮到WPF/Silverlight基於XAML! – Jacques 2014-04-25 09:37:31

回答

1

1)將DrawingImage.xaml添加到項目中,並將其屬性設置爲「BuildAction = Content」和「始終複製」。否則,您可以從外部動態加載XAML,因爲我將要解釋的邏輯也適用於loose-xaml。

2)寫轉換到XAML的URI的UIElement轉換,在你的情況下,將始終DrawingImage

public class FileToUIElementConverter :IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     FileStream fileStream = new FileStream((string)parameter, FileMode.Open); 
     return XamlReader.Load(fileStream) as DrawingImage; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

3)寫出XAML如下

<Window.Resources> 
    <local:FileToUIElementConverter x:Key="uriToUIElementConverter"/> 
</Window.Resources> 
<Grid> 
    <Image Stretch="Fill" Source="{Binding Converter={StaticResource uriToUIElementConverter},ConverterParameter=ImageDrawing.xaml}"/> 
</Grid> 
+0

我不認爲FileStream可以從編譯資源(pack:// URI)加載,可以嗎? – 2009-07-10 12:37:58

+0

我嘗試了上面提到的方法,它運行良好。 – 2009-07-10 18:47:45

+0

有一個轉換器可以在這裏處理資源:http://stackoverflow.com/a/21588195/418362 – Artfunkel 2014-05-25 18:12:12

8

您可以直接引用您的矢量圖形爲StaticResources:

<Image Source="{StaticResource MyImage}" /> 

將圖像存儲在ResourceDict像DrawImage一樣離子。 Expression Blend可以幫助您生成這些東西:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

    <DrawingImage x:Key="MyImage"> 
     <DrawingImage.Drawing> 
     <DrawingGroup> 
      <DrawingGroup.Children> 
       <GeometryDrawing Brush="Black" Geometry="M 333.393,... 100.327 Z "/> 
       <GeometryDrawing Brush="Black" Geometry="F1 M 202.309,... Z "/> 
         : 
      </DrawingGroup.Children> 
     </DrawingGroup> 
    </DrawingImage.Drawing> 
    </DrawingImage> 

</ResourceDictionary> 
1

嵌入類型爲「Resource」的XAML資源(DrawingImage)。它不是一個單獨的文件,並且可以通過URI直接引用,就像在你的原始示例中那樣 - 但是URI是非平凡的。你必須弄清楚微軟的「pack」URI語法並使用它。