XAML 从资源中识别对象

问题描述 投票:0回答:1

我想确定单击了 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

c# wpf xaml
1个回答
0
投票

感谢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;
© www.soinside.com 2019 - 2024. All rights reserved.