使用XAML / WPF做一些简单的事情似乎有很多问题 - 我使用Rectangle和Ellipse等形状创建了一些基于XAML的图像来创建我需要应用程序的其他部分使用的图标 - 但我似乎无法找到如何做到这一点 - 我似乎能够在资源字典中存储Canvas但无法在任何其他窗口中使用它。这是怎么做的 - 这些是我想在整个项目中使用的两三个形状的简单图像!
图像也必须可调整大小 - 我知道如何存储路径,但是这些形状包含我想保留的渐变样式,而且我不知道矩形如何转换为路径和颜色数据。
谢谢!
答案 0 :(得分:7)
您应该使用Drawing并使用DrawingBrush(如KP Adrian建议)或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>
答案 1 :(得分: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>
我假设您知道如何在您的应用程序中引用此资源字典。
要使用资源,您只需将它们分配给相应的属性即可。对于形状类型的图像,您可以将它们分配给类似于矩形的Fill属性(有很多其他方法,但这很简单)。这是一个例子:
<Button>
<Grid>
<Rectangle Fill="{StaticResource YourResourceKey}" />
</Grid>
</Button>