【问题标题】:How to find either header or row is double clicked on datagrid wpf如何在datagrid wpf上双击查找标题或行
【发布时间】:2012-10-17 06:01:13
【问题描述】:

我在 wpf 应用程序中添加了一个数据网格。

<DataGrid ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" MouseDoubleClick="DataGrid_MouseDoubleClick" />

这是我的代码

private void DataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    if selected row is header
        then do this
    else
        do this
}

现在的问题是我是如何知道哪一个被双击的。它是标题或行。我怎样才能找到它。

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    不是在 DataGrid 中添加双击事件,而是为 DataGridRow 和 DataGridColumnHeader 添加单独的事件。 更新 XAML:

    <DataGrid ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" MouseDoubleClick="DataGrid_MouseDoubleClick"> 
        <DataGrid.Resources>
            <Style TargetType="DataGridRow">
                <EventSetter Event="MouseDoubleClick" Handler="DataGridRow_MouseDoubleClick" />
            </Style>
        </DataGrid.Resources>
        <DataGrid.Resources>
            <Style TargetType="DataGridColumnHeader">
                <EventSetter Event="MouseDoubleClick" Handler="DataGridColumnHeader_MouseDoubleClick" />
            </Style>
        </DataGrid.Resources>
    </DataGrid>
    

    这是后面的代码。

    private void DataGridRow_MouseDoubleClick(object sender, System.Windows.RoutedEventArgs e)
    {
        // This is when a row is double clicked.
    }
    
    private void DataGridColumnHeader_MouseDoubleClick(object sender, System.Windows.RoutedEventArgs e)
    {
        // This is when header is double clicked.
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 VisualTreeHelper:

      private void DataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
      {
              var dep = e.OriginalSource as DependencyObject;
              //go up the tree until you find the header
              while (dep != null && !(dep is DataGridRowHeader)) {
                  dep = VisualTreeHelper.GetParent(dep);
              }
              //header found
              if (dep is DataGridRowHeader)
                  //do this
              else //header not found
                  //do that
      }
      

      【讨论】:

      • 它会告诉我我双击了一行或标题,我想这段代码会告诉我gridview是否有标题,
      猜你喜欢
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2013-05-08
      • 2011-08-22
      • 2014-09-27
      • 2014-04-24
      • 1970-01-01
      相关资源
      最近更新 更多