Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

datagrid - Using WPF DataGridHyperLinkColumn Items to open Windows Explorer and open files

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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...