如何在XAML/WPF中存储和检索多个形状?

3
似乎在使用 XAML / WPF 时遇到了很多问题——我已经使用矩形和椭圆等形状创建了基于 XAML 的图像,以创建需要其他部分的应用程序使用的图标。但是我似乎无法找到如何实现此操作的方法。我似乎可以将 Canvas 存储在 Resource Dictionary 中,但没有任何方式在任何其他 Window 中使用它。请问如何完成这个操作?这些都是简单的图像,只有两三个形状,我想在整个项目中使用它们!
同时,这些图像必须可调整大小。我知道如何存储路径,但是这些形状包含要保留的渐变样式,而且我不知道矩形如何转换为路径和颜色数据。

谢谢!

2个回答

7

你应该像KP Adrian建议的那样使用绘图,并使用DrawingBrush进行显示,或者使用DrawingImage和Image控件,但如果你不能使用绘图,可以使用VisualBrush内部的Canvas。

<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>

我假设您已经知道如何将此资源字典引用到您的应用程序中。

要使用资源,您只需将它们分配给相应的属性。对于形状类型的图像,您可以将它们分配给类似于矩形的填充属性(还有很多其他方法,但这是一个简单的方法)。以下是一个示例:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接