基本上,我已经绑定了数据网格,使其类似于科目时间表——每一行代表一个学期的科目,而该学期内的每个单元格代表一个科目。
我现在正在尝试添加拖放功能,以便您可以将其他主题拖到网格上,这将更新底层数据结构。
我可以使用一些可视化树方法来查找用户将新主题拖动到的 DataGridCell,但我不知道如何访问单元格绑定到它的值(主题)以替换空白/新主题的占位符值。有没有办法访问底层价值,或者我应该重新构建创建这个程序的整个方法?
基本上,我已经绑定了数据网格,使其类似于科目时间表——每一行代表一个学期的科目,而该学期内的每个单元格代表一个科目。
我现在正在尝试添加拖放功能,以便您可以将其他主题拖到网格上,这将更新底层数据结构。
我可以使用一些可视化树方法来查找用户将新主题拖动到的 DataGridCell,但我不知道如何访问单元格绑定到它的值(主题)以替换空白/新主题的占位符值。有没有办法访问底层价值,或者我应该重新构建创建这个程序的整个方法?
要获取 DataGridCell 的数据,可以使用它的 DataContext 和Column
属性。如何做到这一点完全取决于您的行数据是什么,即您在ItemsSource
DataGrid 的集合中放置了哪些项目。假设您的项目是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
属性和行数据项转换为行数据项上的特定值。
编辑:
如果您将数据放入的单元格不是选定的单元格,则一种选择是获取DataGridRow
所属的单元格DataGridCell
,使用VisualTreeHelper
:
var parent = VisualTreeHelper.GetParent(gridCell);
while(parent != null && parent.GetType() != typeof(DataGridRow))
{
parent = VisualTreeHelper.GetParent(parent);
}
var dataRow = parent;
然后你就有了行,可以像上面那样继续。
此外,关于您是否应该重新考虑该方法的问题,我建议您使用自定义WPF 行为。
行为提供了一种非常直接的方式来从 C# 代码而不是 XAML 扩展控件的功能,同时保持您的代码隐藏清晰和简单(如果您遵循 MVVM,这不仅很好)。行为的设计方式是它们可重用且不受您特定控件的约束。
对于您的特殊情况,我只能让您知道该怎么做:
DropBehavior
为您的 TextBlock 控件(或您想要在 DataGridCells 中处理拖放的任何控件)编写一个。基本思想是在OnAttached()
控件的方法中将相应的操作注册到单元格的 evnt。
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
属性已过时。
然后,使用DataGridContentTemplate
的将此行为附加到放入单元格中的 TextBlocks :CellStyle
<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
我还没有测试过它,但我希望它对你有用并且你明白了......