我有一个 WPF DataGrid,我在其中按标签显示音乐列表,例如;艺术家、标题、年份等。通过 .itemsource
填充我想要实现的是多选行,并更改列中的值,而不是更改所有选定行的列值。
下面的这个有效,但是它有一些错误,首先,我无法在第一次尝试时选择一个范围,如果我单击一行,例如第一行,然后按住 shift 键单击它下面六行的行,它只会选择这两个,而不是两者之间的所有行。但是,如果我第二次尝试,由于某种原因需要。
我也无法清除选择,换句话说,就像数据网格中选择的正常行为一样,如果我不移动单击网格,而不是单击网格,则只应选择一个项目以清除所有其他项目。
原谅我,我正在努力学习这个……
private void dgPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2 && e.ChangedButton == MouseButton.Left)
{
var hit = VisualTreeHelper.HitTest((Visual)sender, e.GetPosition((IInputElement)sender));
DependencyObject cell = VisualTreeHelper.GetParent(hit.VisualHit);
while (cell != null && !(cell is DataGridCell)) cell = VisualTreeHelper.GetParent(cell);
DataGridCell targetCell = cell as DataGridCell;
DataGridRow row = ItemsControl.ContainerFromElement((DataGrid)sender, e.OriginalSource as DependencyObject) as DataGridRow;
if (targetCell != null)
{
row.IsSelected = true;
DataGridCellInfo _cell = new DataGridCellInfo(targetCell);
dgView.CurrentCell = _cell;
dgView.BeginEdit();
}
}
else if
(Keyboard.Modifiers == ModifierKeys.Shift && e.ChangedButton == MouseButton.Left)
{
return;
}
var dep = (DependencyObject)e.OriginalSource;
// iteratively traverse the visual tree
while ((dep != null) &&
!(dep is DataGridRow))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
if (dep is DataGridRow)
{
var row = dep as DataGridRow;
row.IsSelected = !row.IsSelected;
e.Handled = true;
}
}
FileList类如下:
public class FileList
{
public string Filename { get; set; }
public string FilteredFilename { get; set; }
public string Status { get; set; }
public string Artist { get; set; }
public string Title { get; set; }
public string Year { get; set; }
public string Genre { get; set; }
public string Comments { get; set; }
public bool Updated { get; set; }
}