[英]How do i handle cell double click event on WPF DataGrid, equivalent to windows DataGrid's Events?
如您所知,在 windows C# 的 gridview 中,如果我們要處理單元格上的單擊/雙擊事件,則有 CellClick、CellDoubleClick 等事件。
所以,我想用 WPF DataGrid 做與 windows gridview 一樣的事情。 到目前為止,我已經搜索過,但答案既不適用也不有用。 他們中的一些人說使用 MouseDoubleClick 事件,但在這種情況下,我們必須檢查每一行以及該行中的項目,因此檢查每個單元格的數據很耗時,時間在這里最重要。
我的 DataGrid 綁定到 DataTable 並且 AutoGeneratedColumn 為 False。 如果您的答案基於 AutoGeneratedColumn=True 那么這是不可能的。 甚至,我正在根據數據更改數據網格單元格的樣式,因此無法更改 AutoGeneratedColumn 屬性。
單元格單擊/雙擊事件應該與 Windows 網格的事件一樣快。 如果有可能,請告訴我如何操作,如果沒有,那么有什么替代方法呢?
請幫我.....
非常感謝....
我知道這對派對來說可能有點晚了,但這可能對以后的其他人有用。
在您的 MyView.xaml 中:
<DataGrid x:Name="MyDataGrid" ...>
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="MouseDoubleClick" Handler="DataGridCell_MouseDoubleClick"/>
</Style>
</DataGrid.Resources>
<!-- TODO: The rest of your DataGrid -->
</DataGrid>
在您的 MyView.xaml.cs 中:
private void DataGridCell_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var dataGridCellTarget = (DataGridCell)sender;
// TODO: Your logic here
}
另一種方法是定義DataGridTemplateColumn
而不是使用預定義的列(如DataGridCheckBoxColumn
、 DataGridComboBoxColumn
,然后將事件處理程序添加到數據模板中定義的 UI 元素。
下面我為TextBlock
Cell 定義了一個MouseDown
事件處理程序。
<DataGrid AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock MouseDown="TextBlock_MouseDown"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
在代碼隱藏文件中:
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
TextBlock block = sender as TextBlock;
if (block != null)
{
// Some Logic
// block.Text
}
}
我知道編碼 WPF 有時是一個 PITA。 在這里,您無論如何都必須處理MouseDoubleClick
事件。 然后搜索源對象層次結構以找到DataGridRow
並對其執行任何操作。
更新:示例代碼
XAML
<dg:DataGrid MouseDoubleClick="OnDoubleClick" />
背后的代碼
private void OnDoubleClick(object sender, MouseButtonEventArgs e)
{
DependencyObject source = (DependencyObject) e.OriginalSource;
var row = GetDataGridRowObject(source);
if (row == null)
{
return;
}
else
{
// Do whatever with it
}
e.Handled = true;
}
private DataGridRow GetDataGridRowObject(DependencyObject source)
{
// Write your own code to recursively traverse up via the source
// until you find a DataGridRow object. Otherwise return null.
}
}
我用過這樣的東西:
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding ShowOverlay}" CommandParameter="{Binding Parameter}" />
</DataGrid.InputBindings>
並在我的視圖模型中處理我的命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.