在MouseDown事件中获取形状的WPF名称

本文关键字:WPF 名称 获取 MouseDown 事件 | 更新日期: 2024-10-23 22:30:53

我有一个包含7个形状的用户控件。

<UserControl x:Class="Gramas.OdontogramaUI.PiezaUI"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="280" Width="238.429" Name="EstaPieza" Margin="0,2" Loaded="EstaPieza_Loaded">
    <UserControl.Resources>
        <Style x:Key="Partes" TargetType="{x:Type Rectangle}"/>
    </UserControl.Resources>
    <Grid RenderTransformOrigin="0.5,0.457">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="31*"/>
            <ColumnDefinition Width="45*"/>
            <ColumnDefinition Width="87*"/>
            <ColumnDefinition Width="44*"/>
            <ColumnDefinition Width="31*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="53"/>
            <RowDefinition Height="36*"/>
            <RowDefinition Height="74*"/>
            <RowDefinition Height="41*"/>
            <RowDefinition Height="52*"/>
            <RowDefinition Height="24"/>
        </Grid.RowDefinitions>
        <Viewbox Margin="0,0,0,0" Stretch="Fill" Grid.RowSpan="5" Grid.ColumnSpan="5">
            <Grid Name="ContenedorPieza" Height="299.814" Width="238.429">
                <Path x:Name="Shape1" Data=""/>
                <Path x:Name="Shape2" Data=""/>
                <Path x:Name="Shape3" Data=""/>
                <Path x:Name="Shape4" Data=""/>
                <Path x:Name="Shape5" Data=""/>
                <Path x:Name="Shape6" Data=""/>
                <Path x:Name="Shape7" Data=""/>
            </Grid>
        </Viewbox>
        <TextBlock x:Name="NombrePieza" Text="{Binding ElementName=Esta_Pieza,Path=Pieza.Id}" Grid.Row="5" Margin="0" Height="Auto" Width="Auto" Grid.ColumnSpan="5" Panel.ZIndex="0" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="{DynamicResource {x:Static SystemColors.HotTrackBrushKey}}" FontWeight="ExtraBold"/>
    </Grid>
</UserControl>

每个形状都用x:Shape1命名,我想把mousedown event控制成一个单一的方法

Shape1.MouseDown += Superficie_MouseDown;
Shape2.MouseDown += Superficie_MouseDown;
. . .
private void Superficie_MouseDown(object sender, MouseButtonEventArgs e)
{
    //some stuff here;
}  

我的问题是我无法访问代码背后的发件人姓名,我该如何识别发件人?必须用不同的方法处理。。。。每个形状一个?

在MouseDown事件中获取形状的WPF名称

将发送方键入shape并访问shape的Name属性:

private void Superficie_MouseDown(object sender, MouseButtonEventArgs e)
{
    string name = ((Shape)sender).Name;
}