使用此代码,我只能在MainWindow上获得控制权
Public Shared Function FindChild(Of T As DependencyObject)(ByVal parent As DependencyObject, ByVal childName As String) As T
If parent Is Nothing Then Return Nothing
Dim foundChild As T = Nothing
Dim childrenCount As Integer = VisualTreeHelper.GetChildrenCount(parent)
For i As Integer = 0 To childrenCount - 1
Dim child = VisualTreeHelper.GetChild(parent, i)
Dim childType As T = TryCast(child, T)
If childType Is Nothing Then
foundChild = FindChild(Of T)(child, childName)
If foundChild IsNot Nothing Then Exit For
ElseIf Not String.IsNullOrEmpty(childName) Then
Dim frameworkElement = TryCast(child, FrameworkElement)
If frameworkElement IsNot Nothing AndAlso frameworkElement.Name = childName Then
foundChild = CType(child, T)
Exit For
End If
Else
foundChild = CType(child, T)
Exit For
End If
Next
Return foundChild
End Function
Public sub findControl()
Dim foundTKU As TextBox = FindChild(Of TextBox)(Application.Current.MainWindow, "TKU_" & row("gorivo"))
End sub
我将如何实现相同的内容,而要执行MainWindow来在活动窗口或WPF网格(称为“ controlGrid”)中查找
答案 0 :(得分:1)
只需将活动窗口或控件的实例传递给方法,而不要传递Application.Current.MainWindow
:
Public sub findControl()
Dim foundTKU As TextBox = FindChild(Of TextBox)(controlGrid, "TKU_" & row("gorivo"))
End sub