wpf 如何在datagrid wpf上双击找到标题或行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12928049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:48:23  来源:igfitidea点击:

How to find either header or row is double clicked on datagrid wpf

c#wpfdatagrid

提问by fhnaseer

I added a datagrid in a wpf application.

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

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

and here is my code behind

这是我的代码

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

Now question is how I came to know which one is double clicked. It is header or a row. How I can find it out.

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

回答by fhnaseer

Instead of adding double click event in DataGrid, add sperate event for DataGridRow and DataGridColumnHeader. Updated XAML:

不是在 DataGrid 中添加双击事件,而是为 DataGridRow 和 DataGridColumnHeader 添加 sperate 事件。更新的 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>

And here is code behind.

这是后面的代码。

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

回答by Vale

You can use VisualTreeHelper:

您可以使用 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
}