簡單XAML - 注意SelectionUnit,SelectedCellsChanges和KeyUp事件添加到數據網格
<Window x:Class="WpfApp4.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:WpfApp4"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="MyGrid" HorizontalAlignment="Left" Height="276" Margin="18,21,0,0" VerticalAlignment="Top" Width="466" SelectionUnit="Cell" SelectedCellsChanged="SelectionChanged" KeyUp="MyGrid_PreviewKeyUp"/>
</Grid>
</Window>
一些簡單的C#代碼:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApp4
{
public class MyItems
{
public int Col1 { get; set; }
public int Col2 { get; set; }
public int Col3 { get; set; }
public int Col4 { get; set; }
}
public partial class MainWindow : Window
{
// create a source for the datagrid
public List<MyItems> DataList { get; set; }
// somewhere to hold the selected cells
IList<DataGridCellInfo> DataGridSelectedCells { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
DataList = new List<MyItems>()
{
new MyItems() { Col1=1, Col2=2, Col3=3, Col4=4},
new MyItems() { Col1=5, Col2=6, Col3=7, Col4=8},
new MyItems() { Col1=9, Col2=10, Col3=11, Col4=12},
new MyItems() { Col1=13, Col2=14, Col3=15, Col4=16},
};
MyGrid.ItemsSource = DataList;
}
private void SelectionChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataGridSelectedCells = MyGrid.SelectedCells;
}
private void MyGrid_PreviewKeyUp(object sender, KeyEventArgs e)
{
// Check your key here (Ctrl D, Ctrl R etc)
// then loop around your data looking at what is selected
// chosing the direction based on what key was pressed
foreach (DataGridCellInfo d in DataGridSelectedCells)
{ // get the content of the cell
var cellContent = d.Column.GetCellContent(d.Item);
if (cellContent != null)
{ // if it's not null try to get the content
DataGridCell dc = (DataGridCell)cellContent.Parent;
TextBlock tb = (TextBlock)dc.Content;
// Change the contents of tb.Content here
// or dump for debugging
Console.WriteLine(tb.Text);
}
}
}
}
}
用戶可以拖動細胞在任何方向和「 GridSelectedCells'將只填充選定的單元格。使用KeyUp(或其他首選)事件允許用戶複製(或通過上下文菜單實現右鍵單擊事件),然後根據需要循環數據(向前或向後)進行復制。
雖然它不是一個完整的解決方案,它應該讓你開始。