WPF中的漫游树视图问题
本文关键字:视图 问题 漫游 WPF | 更新日期: 2023-09-27 18:20:26
我使用的是以下示例代码:
private TreeViewItem GetNearestContainer(UIElement element)
{
// Walk up the element tree to the nearest tree view item.
TreeViewItem container = element as TreeViewItem;
while ((container == null) && (element != null))
{
element = VisualTreeHelper.GetParent(element) as UIElement;
container = element as TreeViewItem;
}
return container;
}
在运行时,UIElement
显示为TextBlock
(它实际上是一个被拖动的TreeViewItem
),在这一行:
TreeViewItem container = element as TreeViewItem
即使元素是TextBlock
,容器也总是填充null。这是否意味着它不能正确铸造?我正在尝试使用本文实现Drag and Drop
。
我想你可以遍历可视化树,找到包含你的文本块的TreeViewItem,类似这样。
public static class Exensions
{
/// <summary>
/// Traverses the visual tree for a <see cref="DependencyObject"/> looking for a parent of a given type.
/// </summary>
/// <param name="targetObject">The object who's tree you want to search.</param>
/// <param name="targetType">The type of parent control you're after</param>
/// <returns>
/// A reference to the parent object or null if none could be found with a matching type.
/// </returns>
public static DependencyObject FindParent(this DependencyObject targetObject, Type targetType)
{
DependencyObject results = null;
if (targetObject != null && targetType != null)
{
// Start looking form the target objects parent and keep looking until we either hit null
// which would be the top of the tree or we find an object with the given target type.
results = VisualTreeHelper.GetParent(targetObject);
while (results != null && results.GetType() != targetType) results = VisualTreeHelper.GetParent(results);
}
return results;
}
}
并与线一起使用
TreeViewItem treeViewItem = textBlock.FindParent(typeof(TreeView));