如何在按钮单击时获取行索引和网格列

时间:2012-04-06 08:54:32

标签: c# asp.net silverlight-4.0 silverlight-3.0

我在里面有网格和按钮控件。我想得到的是点击按钮的行索引和列索引。我是silverlight的新手所以请帮帮我

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="testgrid.MainPage"
    Width="640" Height="480">


    <Grid x:Name="LayoutRoot" Background="Azure" Height="400" Width="400" >
        <Grid.ColumnDefinitions >
            <ColumnDefinition Width="100*" />
            <ColumnDefinition Width="100*" />
            <ColumnDefinition Width="100*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="100*" />
            <RowDefinition Height="100*" />
            <RowDefinition Height="100*" />
        </Grid.RowDefinitions>
        <Button x:Name="button1"  Grid.Column="0" Grid.Row="0" Click="grid_Item_Click">
            <Image x:Name="img1" Source="/testgrid;component/Images/kobe_bryant1.jpg" Stretch="Uniform" ></Image>
        </Button>
           <Button x:Name="button2"  Grid.Column="1" Grid.Row="0" Click="grid_Item_Click">
            <Image x:Name="img2" Source="/testgrid;component/Images/kobe_bryant1.jpg" Stretch="Uniform" ></Image>
        </Button>
           <Button x:Name="button3"  Grid.Column="2" Grid.Row="0" Click="grid_Item_Click">
            <Image x:Name="img3" Source="/testgrid;component/Images/kobe_bryant1.jpg" Stretch="Uniform" ></Image>
        </Button>
           <Button x:Name="button4"  Grid.Column="0" Grid.Row="1" Click="grid_Item_Click">
            <Image x:Name="img4" Source="/testgrid;component/Images/kobe_bryant1.jpg" Stretch="Uniform" ></Image>
        </Button>   
    </Grid>
</UserControl>

及其背后的页面

 private void grid_Item_Click(object sender, RoutedEventArgs e)
        {
}

1 个答案:

答案 0 :(得分:2)

你可以试试这个

private void grid_Item_Click(object sender, RoutedEventArgs e) 
{ 
Button btn = sender as Button; 
int x=(int)btn.GetValue(Grid.RowProperty); 
int y=(int)btn.GetValue(Grid.ColumnProperty);  
  MessageBox.Show("row"+x.ToString()+"column"+y.ToString());
 }