I have a VB class inside which one of the methods accepts an array of forms.
For each form inside the array, I need it to traverse all of the objects, check if they are a specific tyoe (input, label, checkbox, etc.) and get the properties of each object. Then, I want to dump these into a text file in the following format:
Form1 | Label1 | "Ente开发者_如何学Cr your name"
"Enter your name" being the caption or text of the form object.
I want to do this to facilitate the translation of an application. Any ideas or thoughts you might have on this?
The following code will return an IEnumerable(Of Control)
which contains all child controls of the passed in control. It will recursively descend down the tree and get all nested controls.
Public Function GetAllControls(ByVal source as Control) As IEnumerable(Of Control)
Dim seq = Enumerable.Empty(Of Control)
For Each child in source.Controls
if child.Controls.Count > 0 Then
seq = seq.Concat(GetAllControls(child))
End If
Next
Return seq
End Function
You have to do a For Each for the form's .Controls collection. However, note that if a child control of the form has more controls in its own .Controls collection, they won't be accounted for. You'll have to make a recursive function in order to traverse the whole parent-child chain of controls to find them all.
Now, for each control, you'll want to perhaps do a Case statement to check the Type Of for each control. Then cast the control to it's type and grab the properties.
If all you want to do is to be able to localise your form then a much simpler way would be to set the form's Localizable property to true. This will result in the creation of a .resx file containing all the values of the various properties for all the controls on the form so that the texts etc can be translated and distributed as a separate satellite assembly.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ProcessForm(Me)
End Sub
Private Sub ProcessForm(ByVal frm As Form)
For Each el As Control In frm.Controls
Dim str As String
str = String.Format("{0} | {1} | {2}", frm.Name.ToString(), el.Name.ToString(), el.Text.ToString())
Debug.Print(str)
Next
End Sub
End Class
精彩评论