XAML从资源中识别对象

zy1mlcev  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(116)

我想确定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 s或GeometryDrawing s?

4nkexdtk

4nkexdtk1#

感谢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;

相关问题