Search code examples
wpfvb.netclassparameterstelerik

Passing Class type as parameter


I'm using Telerik controls UI for WPF and they have a StyleManager.ApplicationTheme. Each "theme" is a class Telerik.Windows.Controls.CrystalTheme and each theme has a "palette" Telerik.Windows.Controls.CrystalPalette (public NotInheritable Class) ... example:

Telerik.Windows.Controls.CrystalPalette
Telerik.Windows.Controls.GreenPalette
Telerik.Windows.Controls.MaterialPalette
' ... etc. (about 19 of them)

' All valid assignments
CrystalPalette.Palette.FontSizeXS = 8
MaterialPalette.Palette.FontSizeL = 14

I'm tring to setup a Sub that will set FontSizes based on the ThemePalette ... example:

Public Function DoSomething() As Boolean
' ...
   ApplyThemeFontSizes(CrystalPalette)
' ...
End Function

Private Sub ApplyThemeFontSizes(Of T)()

     Try

         T.Palette.FontSizeXS = 8
         T.Palette.FontSizeS = 10
         T.Palette.FontSize = 12
         T.Palette.FontSizeL = 14
         T.Palette.FontSizeXL = 16

     Catch ex As Exception

         ' TODO: Log error to file (possible the Theme doesn't have a "Palette")

     End Try

End Sub

This code doesn't work and I'm trying to jog my memory on how I can make this work without using Reflection. I don't have any control over the Telerik classes.

I've searched for similar, but the results were not what I'm trying to achieve (i.e. I don't have control over the Telerik classes).

Suggestions?


Solution

  • I ended up using Reflection which is last resort since Reflection is so slow ... fortunately the call instance is usually one time at startup and when the user changes a theme.

    ApplyThemeFontSizes(Office2019Palette.Palette)
    
        Private Sub ApplyThemeFontSizes(ByVal palette As ThemePalette)
    
        Try
    
            TrySetPaletteProperty(palette, "FontSizeXS", 10 + Me.FontOffset)
            TrySetPaletteProperty(palette, "FontSizeS", 12 + Me.FontOffset)
            TrySetPaletteProperty(palette, "FontSize", 14 + Me.FontOffset)
            TrySetPaletteProperty(palette, "FontSizeL", 16 + Me.FontOffset)
            TrySetPaletteProperty(palette, "FontSizeXL", 18 + Me.FontOffset)
    
        Catch ex As Exception
    
            ' TODO: Log error to file 
    
        End Try
    
    End Sub
    
    Private Sub TrySetPaletteProperty(ByVal palette As ThemePalette, ByVal propertyName As String, ByVal newValue As Object)
    
        Try
    
            ' Set FontSize property values
            Dim propertyInfo = palette.[GetType]().GetProperty(propertyName)
            If propertyInfo IsNot Nothing Then
                propertyInfo.SetValue(palette, newValue)
            End If
    
        Catch ex As Exception
    
            ' TODO: Log error to file 
    
        End Try
    
    End Sub