2013-12-17 43 views
0

我有一個帶有7個形狀的用戶控件。在MouseDown事件中獲取WPF形狀名稱

<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; 
} 

我的問題是我不能在我的代碼訪問發件人的名稱背後,如何我可以做識別發件人嗎?必須用不同的方法來處理......每種形狀都有一個?

+0

你能在繼承和添加的getName()funtion定義自己的形狀。這樣,您可以將/ [as](http://msdn.microsoft.com/zh-cn/library/cscsdfbt.aspx)從發件人轉換爲您的課程並調用您的函數。 –

+0

您的鼠標向下事件有發件人。 – Sampath

+0

mmmm非常醜陋的事情,因爲我的形狀已經有了一個名字。 –

回答

1

類型轉換髮件人塑造和形狀的訪問Name屬性:

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

或'string name =(sender as Shape).Name;' –

+0

我看到沒有問題直接投射。 –

+0

@Rohit Vats Very tks,你知道爲什麼'(Shape)sender''不起作用嗎? –