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

时间:2013-12-17 11:47:04

标签: c# wpf

我有一个包含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;
}  

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

1 个答案:

答案 0 :(得分:1)

Typecast发送者塑造和访问形状的名称属性:

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