如何在代码中访问DataGridCell的数据对象?

Mig*_*ell 7 c# data-binding wpf datagrid c#-4.0

基本上我绑定了数据网格,使其类似于主题的时间表 - 每行代表一个学期的学科,并且该学期内的每个单元代表一个主题.

我现在正在尝试添加拖放功能,以便您可以将其他主题拖动到网格上,这将更新基础数据结构.

我可以使用一些可视树方法来查找用户正在拖动新主题的DataGridCell,但我不知道如何访问单元格绑定到它的值(主题)以替换空白/占位符值与新主题.有没有办法访问基础值或者我应该重构我创建此程序的整个方法?

网格和要拖动到其上的主题的示例

Mar*_*arc 3

要获取DataGridCell的数据,您可以使用它的DataContext和属性Column。如何做到这一点完全取决于您的行数据是什么,即您将哪些项目放入ItemsSourceDataGrid 集合中。假设您的项目是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];
Run Code Online (Sandbox Code Playgroud)

如果您的行数据更复杂,您需要编写一个相应的方法,将Column属性和行数据项转换为行数据项上的特定值。


编辑:

如果您将数据放入的单元格不是选定的单元格,一种选择是获取DataGridRow该单元DataGridCell格所属的单元格,使用VisualTreeHelper

var parent = VisualTreeHelper.GetParent(gridCell);
while(parent != null && parent.GetType() != typeof(DataGridRow))
{
    parent = VisualTreeHelper.GetParent(parent);
}
var dataRow = parent;
Run Code Online (Sandbox Code Playgroud)

然后您就拥有了该行并可以按照上面的方式继续。


此外,关于您是否应该重新考虑该方法的问题,我建议使用自定义WPF 行为

行为提供了一种非常直接的方法来从 C# 代码(而不是 XAML)扩展控件的功能,同时保持代码隐藏清晰和简单(如果您遵循 MVVM,这不仅是件好事)。行为的设计方式是可重用且不受您的特定控制的约束。

这里有一个很好的介绍

对于你的特殊情况,我只能告诉你该怎么做:

DropBehavior为您的 TextBlock 控件(或者您想要在 DataGridCells 中处理拖放的任何控件)编写一个控件。基本思想是根据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;

    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,从行数据解析单个单元格的数据和Column属性已过时。

ContentTemplate然后,使用CellStyleDataGrid 的将此行为附加到 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>
Run Code Online (Sandbox Code Playgroud)

您可以Behavior<T>在中找到基类

系统.Windows.Interactivity.dll

我还没有测试过,但我希望它对你有用并且你明白了......