WPF的DataGrid中DataGridHyperlinkColumn的用法
1、添加DataGridHyperlinkColumn列后,xaml如下:
<Window x:Class="WpfDataGridLink.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<DataGrid AutoGenerateColumns="False" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479" HeadersVisibility="None" Background="{x:Null}" Foreground="#FF3939EB">
<DataGrid.Columns>
<DataGridHyperlinkColumn Header="文件列表" Width="479" Binding="{Binding Path=FullFileName}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
2、实现效果,点击一个链接打开链接对应的文件,方法:在DataGrid的首标签内添加 Hyperlink.Click="dataGrid1_Click"属性,即DataGrid中链接的单击事件
3、代码如下:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
DataColumn col=new DataColumn("FullFileName",typeof(string));
dt.Columns.Add(col);
DataRow dr = dt.NewRow();
dr[0] = "D://openFile//anote.xml";
dt.Rows.Add(dr);
DataRow dr2 = dt.NewRow();
dr2[0] = "D://openFile//UserConfig.xml";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "D://openFile//搜索与主机属性.pdf";
dt.Rows.Add(dr3);
dataGrid1.ItemsSource = dt.DefaultView;
}
private void dataGrid1_Click(object sender, RoutedEventArgs e)
{
if (dataGrid1.SelectedItem == null)
{
return;
}
string fileName=(dataGrid1.SelectedItem as DataRowView)[0].ToString();
if (System.IO.File.Exists(fileName))
{
Process.Start(fileName); //打开文件
}
}