使用 WPF DataGridHyperLinkColumn Items 打开 Windows 资源管理器并打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5764951/
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-08 22:49:41  来源:igfitidea点击:

Using WPF DataGridHyperLinkColumn Items to open Windows Explorer and open files

wpfdatagridhyperlinkuri

提问by Yoni

I want to achieve the following:

我想实现以下目标:

Create a WPF DataGrid that have 2 columns:

创建一个具有 2 列的 WPF DataGrid:

The first will have items showing paths to directories, in a hyperlink style. Clicking on a hyperlink will open Windows Explorer in the path specified by the item.

第一个将以超链接样式显示目录路径的项目。单击超链接将在项目指定的路径中打开 Windows 资源管理器。

The second will have items showing paths to files, in a hyperlink style. Clicking on a hyperlink will launch the file, with the default application defined by Windows.

第二个将以超链接样式显示文件路径的项目。单击超链接将使用 Windows 定义的默认应用程序启动文件。

I don't know if it's the right choice, but I added DataGridHyperlinkColumn's to my DataGrid. One problem was to add Uri items that do not refer to an internet locations. Another problem was to handle the clicks in a way that does not open a web browser.

我不知道这是否是正确的选择,但我将 DataGridHyperlinkColumn 添加到我的 DataGrid 中。一个问题是添加不涉及互联网位置的 Uri 项目。另一个问题是以不打开网络浏览器的方式处理点击。

Anyone can help?

任何人都可以帮忙吗?

回答by H.B.

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.

如果 URI 指向一个网站,它将使用默认的 Web 浏览器打开,如果它是一个文件夹,它将在资源管理器中打开,如果它是一个文件,它将使用与其关联的默认应用程序打开。



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

要将其用于自动生成的列,您的属性需要具有类型,Uri以便DataGridHyperlinkColumn生成 a。然后,您可以通过将样式放在 中来连接事件DataGrid.Resources

<DataGrid.Resources>
    <Style TargetType="Hyperlink">
        <EventSetter Event="Click" Handler="DG_Hyperlink_Click"/>
    </Style>
</DataGrid.Resources>