WPF 使用 VisualTreeHelper 垂直和水平查找元素

问题描述 投票:0回答:1

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

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

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

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

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

c# wpf visual-tree visualtreehelper
1个回答
5
投票

没有水平搜索,

class VisualTreeHelpers
可以帮助您在 WPF 的可视化树上导航。通过导航您可以实现各种搜索。

这是最有效的方法,因为它是专门针对您的要求的.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");
© www.soinside.com 2019 - 2024. All rights reserved.