小型WPF程序的源代码如下所示。它在c:\windows
中的DataGrid
下列出了目录。该名称是可以单击以在资源管理器中打开目录的链接。
(这只是一个概念证明程序,用于说明问题。)
是这样的:
我不仅要单击链接来运行打开操作,还希望对其进行设置,以便用户在突出显示一行时可以按o
键来运行公开行动。
设置此内容的好方法是什么?请注意,该程序主要是在C#中指定的,而不是XAML,因此,请尽可能在C#中发布解决方案。但是,如有必要,也欢迎使用XAML答案!
MainWindow.xaml
:
<Window x:Class="WpfFilesDataGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfFilesDataGrid"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
MainWindow.xaml.cs
:
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
namespace WpfFilesDataGrid
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var data_grid = new DataGrid()
{
IsReadOnly = true,
AutoGenerateColumns = false,
ItemsSource = new DirectoryInfo(@"c:\windows").GetDirectories()
};
{
var setter = new EventSetter()
{
Event = Hyperlink.ClickEvent,
Handler = (RoutedEventHandler)((sender, e) =>
{
System.Diagnostics.Process.Start((data_grid.SelectedItem as DirectoryInfo).FullName);
})
};
var style = new Style();
style.Setters.Add(setter);
var col = new DataGridHyperlinkColumn()
{
Header = "FullName",
Binding = new Binding("FullName"),
ElementStyle = style
};
data_grid.Columns.Add(col);
}
data_grid.Columns.Add(new DataGridTextColumn()
{
Header = "CreationTime",
Binding = new Binding("CreationTime")
});
var dock_panel = new DockPanel();
dock_panel.Children.Add(data_grid);
Content = dock_panel;
}
}
}
答案 0 :(得分:1)
You could for example handle the PreviewKeyDown
event:
data_grid.PreviewKeyDown += (s, e) =>
{
if(e.Key == Key.O && data_grid.SelectedItem is DirectoryInfo di)
System.Diagnostics.Process.Start(di.FullName);
};