【问题标题】:How to store and retrieve multiple shapes in XAML/WPF?如何在 XAML/WPF 中存储和检索多个形状?
【发布时间】:2009-02-02 16:48:39
【问题描述】:
似乎在使用 XAML / WPF 做应该简单的事情时遇到了很多问题 - 我已经使用矩形和椭圆等形状创建了一些基于 XAML 的图像来创建我需要应用程序的其他部分使用的图标 -但我似乎无法找到如何做到这一点 - 我似乎能够将 Canvas 存储在资源字典中,但无法在任何其他窗口中使用它。这是如何完成的 - 这些是简单的图像,只是我想在整个项目中使用的两个或三个形状!
图像还必须可调整大小 - 我知道如何存储路径,但是这些形状包含我想要保留的渐变样式,而且我不知道矩形如何转换为路径和颜色数据。
谢谢!
【问题讨论】:
标签:
wpf
vb.net
xaml
resources
shape
【解决方案1】:
您应该使用绘图并使用 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>
【解决方案2】:
您不想使用 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>