Vla*_*lad 9 c# wpf resources xaml
我想在一些WPF应用程序/库中重用一些XAML片段作为图像.
问题的背景如下:
在WPF应用程序中重用位图图像很容易.图像可以作为资源添加,我可以<Image Source="packURI"/>在XAML中的许多地方使用,因此图像将是相同的.
但是我想有可能对矢量图像做同样的事情.图像本身可以表示为Path,但我不能重复Path使用它作为资源,因为禁止在几个不同的地方(可能来自几个UI线程)使用它(UI元素只能有一个逻辑父元素).
而且,如果我想从几个Paths 构建"图像",那么问题会变得更加复杂Canvas.或者一些任意的XAML代码.
我尝试使用一Style对Path,因此,图像被以这样的方式表示:
<Path Style={StaticResource VectorImage1}/>
Run Code Online (Sandbox Code Playgroud)
这似乎是一种可重用的方式,但我关注两个问题:
Path(例如)Canvas,我将不仅需要在样式中替换它,而且还需要在使用它的源代码中的任何地方替换它.Canvas或任意XAML代码的方法.通过定义a UserControl,还有其他方法可以获得可重用的XAML片段,但是为每个矢量图像定义单独的用户控件似乎是一种过度杀伤力.
是否有更好,更好,正确的方法来定义可重用的XAML片段?
Fre*_*lad 15
您可以将x:Shared属性添加到Path Resource并将其用作StaticResource.如果"MyVectorImage"更改为其他内容,则此方法有效
更新
可能更好地使用ContentControl或类似的东西来添加属性,例如保证金等.
<Window.Resources>
<Path x:Key="MyVectorImage"
x:Shared="False"
Stroke="DarkGoldenRod"
StrokeThickness="3"
Data="M 10,20 C 10,25 40,35 40,17 H 28"
Stretch="Fill"
Width="100"
Height="40"/>
</Window.Resources>
<StackPanel>
<ContentControl Margin="10" Content="{StaticResource MyVectorImage}"/>
<ContentControl Margin="10" Content="{StaticResource MyVectorImage}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
例.您将"MyVectorImage"替换为包含两个路径的StackPanel.
<Window.Resources>
<StackPanel x:Key="MyVectorImage"
x:Shared="False">
<Path Stroke="DarkGoldenRod"
StrokeThickness="3"
Data="M 10,20 C 10,25 40,35 40,17 H 28"
Stretch="Fill"
Width="100"
Height="40"/>
<Path Stroke="DarkGoldenRod"
StrokeThickness="3"
Data="M 10,20 C 10,25 40,35 40,17 H 28"
Stretch="Fill"
Width="100"
Height="40"/>
</StackPanel>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
经过一些研究,还有一个选择:使用DrawingImageas作为Source图像.习惯的图像源是a BitmapSource,但它也可以是"矢量图形".
这是一个例子:
<Image>
<Image.Source>
<DrawingImage PresentationOptions:Freeze="True">
<DrawingImage.Drawing>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<GeometryGroup>
<EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" />
<EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" />
</GeometryGroup>
</GeometryDrawing.Geometry>
<GeometryDrawing.Brush>
<LinearGradientBrush>
<GradientStop Offset="0.0" Color="Blue" />
<GradientStop Offset="1.0" Color="#CCCCFF" />
</LinearGradientBrush>
</GeometryDrawing.Brush>
<GeometryDrawing.Pen>
<Pen Thickness="10" Brush="Black" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
Run Code Online (Sandbox Code Playgroud)
产生这样一个漂亮的矢量图像:

另一种选择可能是使用a DrawingBrush,就像在这个SO问题中:如何在XAML/WPF中存储和检索多个形状?.
| 归档时间: |
|
| 查看次数: |
5634 次 |
| 最近记录: |