Wednesday, February 20, 2013

Silverlight Auto Focus on InputBox of TabItem when TabControl changed.


    Private Sub SkuTabControl_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs) Handles SkuTabControl.SelectionChanged
        If SkuTabControl.SelectedItem IsNot Nothing Then
            Dim itemTab As TabItem = SkuTabControl.SelectedItem
            Dim itemGrid As Grid = itemTab.Content
            AddHandler itemGrid.Loaded, AddressOf itemGrid_Loaded
            'itemGrid.LoadedEvent()
        End If
    End Sub

    Private Sub itemGrid_Loaded(ByVal sender As Object, ByVal e As EventArgs)
        Dim itemTab As TabItem = SkuTabControl.SelectedItem
        Dim itemGrid As Grid = itemTab.Content
        Dim customInputBoxes = GetInputBoxControls(itemGrid).OfType(Of CustomTextBox.CustomTextBox)()
        Dim cTextBox As CustomTextBox.CustomTextBox
        For Each cTextBox In customInputBoxes.ToList
            If CType(cTextBox.Background, SolidColorBrush).Color = Color.FromArgb(255, 255, 255, 0) Then
                cTextBox.Focus()
                Exit For
            End If
        Next
    End Sub

    Private Function GetInputBoxControls(ByVal root As DependencyObject) As IEnumerable(Of DependencyObject)
        Try
            Dim customBoxList As New List(Of DependencyObject)()
            customBoxList.Add(root)
            For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(root) - 1
                customBoxList.AddRange(GetInputBoxControls(VisualTreeHelper.GetChild(root, i)))
            Next i
            Return customBoxList
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

No comments: