我想确定单击了 xaml 中的哪个形状。
为此,我通过静态资源向 WPF 添加了图像:
<Image Source="{StaticResource di_input}" Name="MyImage" PreviewMouseDown="OnMouseDown">
此资源是导出的 svg:
<ResourceDictionary
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<DrawingGroup x:Key="easy_xaml">
<DrawingGroup.ClipGeometry>
<RectangleGeometry Rect="0.0,0.0,203.71425,107.84938"/>
</DrawingGroup.ClipGeometry>
<DrawingGroup Transform="1.0,0.0,0.0,1.0,-5.6774192,-3.2151276">
<GeometryDrawing Brush="#ffff6600" x:Name="Rectangle">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="5.6774192,5.3225808,106.45161,69.548386"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
.
.
.
<DrawingImage Drawing="{StaticResource easy_xaml}" x:Key="di_input"/>
</ResourceDictionary>
我可以得到点击所落在的
GeometryDrawing
,但我无法识别它对应于资源中的哪个形状。我添加的 x:Name
属性/值似乎无法访问。
有没有办法访问
Name
或以某种方式区分 DrawingGroup
或 GeometryDrawing
?
感谢BionicCode的提示,我能够想出一个解决方案:自定义附加属性
属性的类别:
public class ShapeId : DependencyObject
{
public static readonly DependencyProperty NameProperty =
DependencyProperty.RegisterAttached(
"Name",
typeof(string),
typeof(ShapeId),
new PropertyMetadata(string.Empty)
);
public static void SetName(UIElement element, string value)
{
element.SetValue(NameProperty, value ?? string.Empty);
}
public static string GetName(UIElement element)
{
return (string)element.GetValue(NameProperty);
}
}
添加到资源中:
<ResourceDictionary
.
.
xmlns:visu="clr-namespace:MyVisu">
.
.
<GeometryDrawing Brush="#ffff6600" visu:ShapeId.Name="Rectangle">
然后可以用
提取var name = hitGeometryDrawing.GetValue(ShapeId.NameProperty) as string;