3

我在 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
}

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

4

2 回答 2

6

不是在 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.
}
于 2012-10-17T09:06:41.293 回答
0

您可以使用 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
}
于 2012-10-17T06:30:59.593 回答