[英]DataGrid - key to run event handler on current item
The source to a small WPF program is shown below. 小型WPF程序的源代码如下所示。 It lists the directories under c:\\windows
in a DataGrid
. 它列出了DataGrid
c:\\windows
下的目录。 The name is a link that can be clicked to open the directory in Explorer. 该名称是可以单击以在资源管理器中打开目录的链接。
(This is just a proof of concept program to illustrate the question.) (这只是一个概念证明程序,用于说明问题。)
Here's what it looks like: 看起来是这样的:
Instead of only being able to click on the link to run the open action, I'd also like to set it up so that the user can press the o
key when a row is highlighted in order to run the open action. 我不仅希望单击链接来运行打开动作,还希望对其进行设置,以便用户在突出显示一行时可以按o
键以运行打开动作。
What's a good way to set this up? 进行此设置的好方法是什么? Note that the program is primarily specified in C# as opposed to XAML so if possible, please post your solution in C#. 请注意,该程序主要是在C#中指定的,而不是XAML,因此,请尽可能在C#中发布解决方案。 However, if necessary, XAML answers are welcome too! 但是,如有必要,也欢迎XAML答案!
MainWindow.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
: 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;
}
}
}
You could for example handle the PreviewKeyDown
event: 例如,您可以处理PreviewKeyDown
事件:
data_grid.PreviewKeyDown += (s, e) =>
{
if(e.Key == Key.O && data_grid.SelectedItem is DirectoryInfo di)
System.Diagnostics.Process.Start(di.FullName);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.