要获取 DataGridCell 的数据,您可以使用它的 DataContext 和 Column 属性。如何做到这一点完全取决于您的行数据是什么,即您在 DataGrid 的 ItemsSource 集合中放入了哪些项目。假设您的项目是 object[] 数组:
// Assuming this is an array of objects, object[],this gets you the
// row data as you have them in the DataGrid's ItemsSource collection
var rowData = (object[]) DataGrid.SelectedCells[0].Item;
// This gets you the single cell object
var celldata = rowData[DataGrid.SelectedCells[0].Column.DisplayIndex];
如果您的行数据更复杂,您需要编写一个相应的方法,将Column 属性和行数据项转换为行数据项上的特定值。
编辑:
如果您将数据放入的单元格不是选定的单元格,一种选择是使用VisualTreeHelper 获取DataGridCell 所属的DataGridRow:
var parent = VisualTreeHelper.GetParent(gridCell);
while(parent != null && parent.GetType() != typeof(DataGridRow))
{
parent = VisualTreeHelper.GetParent(parent);
}
var dataRow = parent;
那么你就有了行并且可以像上面那样继续。
此外,关于您是否应该重新考虑该方法的问题,我建议您使用自定义 WPF 行为。
行为提供了一种非常直接的方式来从 C# 代码而不是 XAML 扩展控件的功能,同时保持代码隐藏清晰和简单(如果您遵循 MVVM,这不仅很好)。行为的设计方式使其可重复使用且不受您特定控件的约束。
Here's a good introduction
对于你的特殊情况,我只能告诉你该怎么做:
为您的 TextBlock 控件(或您想要在 DataGridCells 中处理拖放的任何控件)编写一个 DropBehavior。基本思想是在您的 OnAttached() 方法中为单元格的事件注册相应的操作控制。
public class DropBehavior : Behavior<TextBlock>
{
protected override void OnAttached()
{
AssociatedObject.MouseUp += AssociatedObject_MouseUp;
}
private void AssociatedObject_MouseUp(object sender, MouseButtonEventArgs e)
{
// Handle what happens on mouse up
// Check requirements, has data been dragged, etc.
// Get underlying data, now simply as the DataContext of the AssociatedObject
var cellData = AssociatedObject.DataContext;
}
}
请注意,从行数据和Column 属性解析单个单元格的数据已过时。
然后,您使用 DataGrid 的 CellStyle 的 ContentTemplate 将此行为附加到 TextBlocks,然后将其放入单元格中:
<DataGrid>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding}">
<i:Interaction.Behaviors>
<yourns:DropBehavior/>
</i:Interaction.Behaviors>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.CellStyle>
</DataGrid>
您可以在
中找到
Behavior<T> 基类
System.Windows.Interactivity.dll
我没有测试过它,但我希望它对你有用并且你明白了......