0

I have a user of one of my applications who is getting a exception when he uses the Window Classic theme.The exception occurs with the following code:

    ' Add to listbox and scroll to end
    '
    Dim iLast As UInt32 = lstStatus.Items.Add(theStatus)

    If VisualTreeHelper.GetChildrenCount(lstStatus) > 0 Then
        Dim oBorder As Border = VisualTreeHelper.GetChild(lstStatus, 0)
        Dim oScrollViewer As ScrollViewer = VisualTreeHelper.GetChild(oBorder, 0)
        oScrollViewer.ScrollToBottom()
    End If

The exception is thrown on the line assigning the return of "GetChild" to a Border variable. With Windows Classic theme the child control returned is a "ClassicBorderDecorator" and there is no cast to a "Border".

The code is attempting to scroll the listbox to the end to ensure the last added item is visible. Is there a way to handle the Classic theme here?

Note my code was based upon an answer to a question here: WPF ListBox Scroll to end automatically

Sid

Community
  • 1
  • 1
Sid
  • 563
  • 6
  • 23

1 Answers1

0

After using the Live Visual Tree to examine my application when it is using the Windows Classic Theme I came up with the following solution. I catch the exception in my original code and then attempt to get a child type of "Decorator". I then use this to recover the ScrollViewer:

    Dim iLast As UInt32 = lstStatus.Items.Add(theStatus)

    If VisualTreeHelper.GetChildrenCount(lstStatus) > 0 Then
        Dim oScrollViewer As ScrollViewer
        Try
            Dim oBorder As Border = VisualTreeHelper.GetChild(lstStatus, 0)
            oScrollViewer = VisualTreeHelper.GetChild(oBorder, 0)
        Catch ex As Exception
            '
            ' Try to get a decorator type, we may be using Windows classic theme or similar
            '
            Try
                Dim oDecorator As Decorator = VisualTreeHelper.GetChild(lstStatus, 0)
                oScrollViewer = VisualTreeHelper.GetChild(oDecorator, 0)
            Catch exInner As Exception
                oScrollViewer = Nothing
            End Try
        End Try
        If oScrollViewer Is Nothing = False Then
            oScrollViewer.ScrollToBottom()
        End If
    End If

If anyone thinks this is not a generic solution I would appreciate a comment.

Thanks, Sid

Sid
  • 563
  • 6
  • 23