重用XAML DrawingImage只改变PathGeometry LineSegments的方法是什么?

时间:2011-02-09 16:33:50

标签: wpf xaml wpf-controls

我的WPF应用程序中有三个按钮,我想显示三角形的图像。我没有使用Shape类,因为它对我的需求来说太重了,所以我使用的是DrawingImage。这是我的图像的标记(我会发布一个看起来很干净的图像但是因为我是新手而不能这样做):

<Image>
    <Image.Source>
        <DrawingImage>
            <DrawingImage.Drawing>
                <GeometryDrawing Brush="LawnGreen">
                    <GeometryDrawing.Pen>
                        <Pen Brush="Black" Thickness="1" />
                    </GeometryDrawing.Pen>
                    <GeometryDrawing.Geometry>
                        <PathGeometry>
                            <PathFigure   IsClosed="True">
                                <LineSegment Point="-10, 20" />
                                <LineSegment Point="30, 20" />
                            </PathFigure>
                        </PathGeometry>
                    </GeometryDrawing.Geometry>
                </GeometryDrawing>
            </DrawingImage.Drawing>
        </DrawingImage>
    </Image.Source>
</Image>

这是第一个按钮的图像 - 一个斜角三角形,其左边是峰值。其他两个按钮的XAML几乎完全相同 - 唯一的变化是线段点分别与它们轴的中间和右侧的峰值略有不同。

如何在没有特定线段坐标的情况下为我的Image.Source-&gt; DrawingImage制作一个声明,然后执行类似

的操作
<Button>  
    <Image Source="MyGenericDrawingImage">  
        <!--*Fill in the PathGeometry>PathFigure> LineSegment coordinates for each button-->  
    </Image>  
</Button>

这看起来比必须将几乎相同的代码块彼此相邻地转储干净得多。

2 个答案:

答案 0 :(得分:2)

我知道这是旧的,但这是我使用的解决方案。我将路径几何设置为资源,并将其作为样式引用(非常适合重复使用)。要使箭头指向侧面,请重复使用相同的图标并将其旋转90度。

enter image description here

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib">

<Page.Resources>
  <sys:String x:Key="Icon_ArrowDown">
          F1 M 4.439,0.000 L 2.219,3.112 L 0.000,0.000 L 4.439,0.000 Z
      </sys:String>
</Page.Resources>

<StackPanel> 

<Button>
   <Path Data="{StaticResource  Icon_ArrowDown}" Fill="Red" />
</Button>

<Button>
    <Path Data="{StaticResource Icon_ArrowDown}" Fill="Red" />
        <Path.RenderTransform>
            <CompositeTransform Rotation="-90"/>
        </Path.RenderTransform>
    </Path>
</Button>

</StackPanel>
</Page>

答案 1 :(得分:0)

除非你有完美的对称,缩放,旋转几何(等),否则你将不得不采取某种形式的数据修改来避免“重复”它。如果它不一致,它实际上是不同的几何形状。

也就是说,您可以编辑代码中的数据并使用数据绑定来获取已编辑的值。

以下是有关如何将路径数据绑定到视图模型中指定的几何体的一些信息:

Path drawing and data binding