2009-02-02 37 views
3

似乎遇到很多问题,使用XAML/WPF做简单的事情 - 我使用Rectangle和Ellipse等形状创建了一些基于XAML的图像,以创建需要使用其他应用程序部分的图标 - 但我似乎无法找到如何做到这一点 - 我似乎能够在资源字典中存储画布,但无法在任何其他窗口中使用它。这是如何完成的 - 这些都是简单的图像,我想在整个项目中使用两三个形状!
图像也必须可调整大小 - 我知道如何存储路径,但是这些形状包含我想要保存的渐变样式,以及我不知道矩形如何转换为路径和颜色数据。如何在XAML/WPF中存储和检索多个形状?

谢谢!

回答

7

您应使用绘图和使用DrawingBrush像KP阿德里安建议或DrawingImage和Image控件中显示,但如果你不能使用绘图你可以使用里面画布VisualBrush。

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
<Page.Resources> 
    <VisualBrush x:Key="Icon"> 
     <VisualBrush.Visual> 
      <Canvas Width="10" Height="10"> 
       <Ellipse Width="5" Height="5" Fill="Red"/> 
       <Ellipse Width="5" Height="5" Fill="Blue" Canvas.Left="5" Canvas.Top="5"/> 
      </Canvas> 
     </VisualBrush.Visual> 
    </VisualBrush> 
</Page.Resources> 
    <Rectangle Width="100" Height="100" Fill="{StaticResource Icon}"/> 
</Page> 
3

您不希望使用Canvas将这些资源存储在资源字典中。几何图形的根源大概就像一个DrawingBrush(特别是如果你使用Expression Design中创建的图像),这些都是需要被添加到资源字典,像这样的项目:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <DrawingBrush x:Key="YourResourceKey"> 
<DrawingBrush.Drawing> 
<DrawingGroup> 
<!-- This can change a lot, but a typical XAML file exported from a Design image would have the geometry of the image here as a bunch of Paths or GeometryDrawings --> 
</DrawingGroup> 
</DrawingBrush.Drawing> 
</ResourceDictionary> 

我假设你知道如何获得你的应用程序中引用的这个资源字典。

要使用资源,只需将它们分配给相应的属性即可。对于形状类型的图像,可以将它们分配给类似Rectangle的Fill属性的东西(还有很多其他方法,但这很简单)。这里有一个例子:

<Button> 
    <Grid> 
     <Rectangle Fill="{StaticResource YourResourceKey}" /> 
    </Grid> 
</Button>