Using WPF DataGridHyperLinkColumn Items to open Windows Explorer and open files

前端 未结 1 544
走了就别回头了
走了就别回头了 2020-12-08 11:25

I want to achieve the following:

Create a WPF DataGrid that have 2 columns:

The first will have items showing paths to directories, in a hyperlink style. Cli

相关标签:
1条回答
  • 2020-12-08 11:46

    This works universally:

    <DataGridHyperlinkColumn Binding="{Binding Link}">
        <DataGridHyperlinkColumn.ElementStyle>
            <Style>
                <EventSetter Event="Hyperlink.Click" Handler="DG_Hyperlink_Click"/>
            </Style>
        </DataGridHyperlinkColumn.ElementStyle>
    </DataGridHyperlinkColumn>
    
    private void DG_Hyperlink_Click(object sender, RoutedEventArgs e)
    {
        Hyperlink link = (Hyperlink)e.OriginalSource;
        Process.Start(link.NavigateUri.AbsoluteUri);
    }
    

    If the URI points a website it will be opened with the default web-browser, if it is a folder it will be opened in explorer, if it is a file it will be opened with the default application associated with it.


    To use this for autogenerated columns your property needs to be of type Uri so a DataGridHyperlinkColumn is generated. You then can hook up the event by placing the style in the DataGrid.Resources:

    <DataGrid.Resources>
        <Style TargetType="Hyperlink">
            <EventSetter Event="Click" Handler="DG_Hyperlink_Click"/>
        </Style>
    </DataGrid.Resources>
    
    0 讨论(0)
提交回复
热议问题