开发者

Using WPF DataGridHyperLinkColumn Items to open Windows Explorer and open files

开发者 https://www.devze.com 2023-02-28 12:23 出处:网络
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. Clicking on a hyperlink will open Windows Ex

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. Clicking on a hyperlink will open Windows Explorer in the path specified by the item.

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.

I don't know if it's the开发者_如何学Python 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.

Anyone can help?


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

精彩评论

暂无评论...
验证码 换一张
取 消