【问题标题】:WPF find element with VisualTreeHelper vertical and horizontalWPF使用VisualTreeHelper垂直和水平查找元素
【发布时间】:2015-12-13 23:57:31
【问题描述】:

在可视化树中垂直和水平搜索最简单的方法是什么?

例如,我想从控件中找到不在父列表中的控件,从而开始搜索。

这是一个简单的例子(每个框代表一些 UI 控件):

例如我从一个嵌套控件开始(Search-Start)并想找到另一个嵌套控件(应该找到)。

最好的方法是什么?解析完整的视觉树好像不是很有效……谢谢!

【问题讨论】:

  • 有效是什么意思?不工作还是不是最有效的方法?假设您对树一无所知,也没有要查找的元素名称,那么只有遍历(可能)整个树才能找到所需的内容。
  • 我的意思是尽可能快:) 我只有这样的信息,即控件必须非常靠近 root 元素,如窗口。我喜欢搜索的控件是RadRibbonView
  • 也许breadth-first 可能会更有效,但你会遍历树。

标签: c# wpf visual-tree visualtreehelper


【解决方案1】:

没有横向搜索,class VisualTreeHelpers谁可以帮助你Navigate on a WPF’s Visual Tree。通过导航,您可以实现各种搜索。

这是最有效的方法,因为它是一个专门满足您要求的 .Net 类。

对于强化:

// Search up the VisualTree to find DataGrid 
// containing specific Cell
var parent = VisualTreeHelpers.FindAncestor<DataGrid>(myDataGridCell);

// Search down the VisualTree to find a CheckBox 
// in this DataGridCell
var child = VisualTreeHelpers.FindChild<CheckBox>(myDataGridCell);

// Search up the VisualTree to find a TextBox 
// named SearchTextBox
var searchBox = VisualTreeHelpers.FindAncestor<TextBox>(myDataGridCell, "SeachTextBox");

// Search down the VisualTree to find a Label
// named MyCheckBoxLabel
var specificChild = VisualTreeHelpers.FindChild<Label>(myDataGridCell, "MyCheckBoxLabel");

【讨论】:

  • 完美运行。我使用Window parentWindow = Window.GetWindow(current); 找到root,然后使用FindChild&lt;RadRibbonView&gt;() 获得我需要的那个:) 谢谢!
  • 我不得不将 @BendEg 的解决方案与 Yael 的解决方案结合起来。谢谢
猜你喜欢
  • 1970-01-01
  • 2013-10-27
  • 2017-05-28
  • 2018-11-19
  • 2018-04-01
  • 1970-01-01
  • 2017-02-28
  • 2012-09-30
相关资源
最近更新 更多