Question How to add a SUB to the base FORM class?

kwanbis

New member
Joined
Sep 3, 2015
Messages
4
Programming Experience
10+
Hello guys. I'm trying to implement an observer class where my forms are added to a list on my TranslationManager, and when the TranslationManager changes the language, all the forms change its language.


The TransLation manager is like this:


VB.NET:
Public Class TranslationManager
    Dim ListOfForms As List(Of Form)


    Public Sub RegisterForm(FormToAdd As Form)
        ListOfForms.Add(FormToAdd)
    End Sub


    Private _Language As String
    Public Property Language() As String
        Get
            Return _Language
        End Get
        Set(ByVal value As String)
            If _Language <> value Then
                _Language = value
                For Each f In ListOfForms
                    f.Translate(_Language)
                Next
            End If
        End Set
    End Property
End Class




Now, the problem is that the base Form class does not has a Translate sub, so the line f.Translate(_Language) is not feasible like it is.


So my question is, how can I modify the base(?) class from where Form2 and Form3 are created so that it includes the Translate sub.


I tried something like:


Public Class myForm


Sub Translate
End Sub


End Class


But when I tell the forms that they inherit from myForm, the designer gets corrupted for that form.


Any ideas?
 
You can extend the Form class instead:

Imports System.Runtime.CompilerServices

Public Module FormExtensions

    <Extension()> _
    Public Sub Translate(ByRef f As Form)
        ...
    End Sub

End Module


Then you can call it like this:

Dim someForm As New Form
someForm.Translate()


You CAN also do it through inheritance, but you will have to modify your form's designer code to inherit from your TranslatableForm. You are doing it the other way around though. Instead, your TranslatableForm class should inherit from Form, and your designer code should instanciate a TranslatableForm instead of a Form. The extension method is just much simpler and cleaner.
 
You can extend the Form class instead:

Imports System.Runtime.CompilerServices

Public Module FormExtensions

    <Extension()> _
    Public Sub Translate(ByRef f As Form)
        ...
    End Sub

End Module


Then you can call it like this:

Dim someForm As New Form
someForm.Translate()


You CAN also do it through inheritance, but you will have to modify your form's designer code to inherit from your TranslatableForm. You are doing it the other way around though. Instead, your TranslatableForm class should inherit from Form, and your designer code should instanciate a TranslatableForm instead of a Form. The extension method is just much simpler and cleaner.

It's unrelated to this issue but that ByRef should be ByVal.
 
Back
Top