22

我希望能够使用矢量图形,最好是在 XAML 中定义,作为图像控件的源,就像我目前可以使用像 PNG 这样的光栅图像一样。这样我就可以轻松地在位图和矢量图像之间混合和匹配,如下所示:

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

Module.xaml 很可能将<DrawingImage>其作为其根元素,而不是<UserControl>.

实际上,我真正想要的是这个,所以我的 ViewModel 可以自行选择光栅或矢量图像:

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

这可能吗?Image.Source 可以从给定的 URI 加载 XAML 类吗?还是只能加载位图资源?

4

3 回答 3

19

您可以简单地将矢量图形引用为 StaticResources:

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

将图像作为 DrawImage 存储在 ResourceDictionary 中。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>
于 2009-07-10T09:19:04.150 回答
2

1) 将 DrawingImage.xaml 添加到项目并将其属性设置为“BuildAction=Content”和“始终复制”。否则,您可以从外部动态加载 XAML,因为我将要解释的逻辑也适用于松散的 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>
于 2009-07-10T05:30:42.020 回答
1

嵌入类型为“资源”的 XAML 资源 (DrawingImage)。然后它不是一个单独的文件,可以通过 URI 直接引用,就像在您的原始示例中一样 - 但 URI 并不重要。您必须弄清楚 Microsoft 的“打包”URI 语法并使用它。

于 2009-10-15T22:28:25.733 回答