如何在网格事件处理程序中单击按钮的行和列?

时间:2010-04-29 03:39:34

标签: c# wpf wpf-controls

单击网格中添加的按钮(窗口控件网格,而不是Gridview或datagrid)后,如何找到按钮位于网格事件处理程序中的哪一行和哪一列,如单击事件或其他一些事件?不是按钮单击事件处理程序

        #region Grid event handler setup
        myGrid.MouseEnter += new MouseEventHandler(myGrid_MouseEnter);
        myGrid.MouseLeave += new MouseEventHandler(myGrid_MouseLeave);
        myGrid.MouseDown += new MouseButtonEventHandler(myGrid_MouseDown);
        myGrid.MouseUp += new MouseButtonEventHandler(myGrid_MouseUp);
        #endregion

由于

我注意到Boyan对按钮点击事件处理程序案例有一些解决方案

In WPF, how can I determine what column/row in a grid a control is in?

在按钮的Click事件处理程序中,您说:

int row; 
Button btn = sender as Button; 
if (btn != null) 
{ 
    row = Grid.GetRow(btn); // And you have the row number... 
} 
else 
{ 
    // A nasty error occurred... 
}

2 个答案:

答案 0 :(得分:2)

请参阅InputHitTest()

UIelement element = (UIelement) Grid.InputHitTest(e.GetPosition(Grid));
row= Grid.GetRow(element); 

答案 1 :(得分:0)

与WPF中的其他所有内容一样,使用数据绑定可能更好。

您可以为按钮构建一个类,并将ItemsSource绑定到它们的集合,而不是使用XmlDataProvider;我正在使用XML,因为它是一个可以轻松复制和粘贴的例子:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
    <XmlDataProvider x:Key="Data">
      <x:XData>
        <Data xmlns="">
          <Button Row="0" Column="0" Text="First"/>
          <Button Row="1" Column="3" Text="Second"/>
          <Button Row="4" Column="4" Text="Third"/>
        </Data>
      </x:XData>
    </XmlDataProvider>
  </Page.Resources>
  <DockPanel Height="300" Width="300">
    <ItemsControl ItemsSource="{Binding Source={StaticResource Data}, XPath=/Data/Button}">
       <ItemsControl.ItemTemplate>
        <DataTemplate>
         <Grid>
          <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
          </Grid.RowDefinitions>
          <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>            
          </Grid.ColumnDefinitions>
           <Button Grid.Row="{Binding XPath=@Row}" 
                   Grid.Column="{Binding XPath=@Column}" 
                   Content="{Binding XPath=@Text}"
                   Click="Button_Click"/>
         </Grid>
        </DataTemplate>
       </ItemsControl.ItemTemplate>
    </ItemsControl>
  </DockPanel>
</Page>

事件处理程序应如下所示(未经测试,因为我在Kaxaml中编写了上述内容):

private void Button_Click(object sender, EventArgs e)
{
   Button b = (Button) sender;
   XmlElement elm = (XmlElement)b.DataContext;
   int row = Convert.ToInt32(elm.GetAttribute("Row"));
   int column = Convert.ToInt32(elm.GetAttribute("Column"));
   // now do whatever you need to do with the row and column
}

这里的关键是按钮的DataContext包含您将用于Click事件的所有信息 - 行和列,当然,还包含您需要关联的任何其他属性用按钮。使用这种方法的工作越多,特定于WPF的代码和标记就会越少。