Wpf 在加载窗口后以编程方式移动列表框中的滚动条

Wpf 在加载窗口后以编程方式移动列表框中的滚动条,wpf,vb.net,listbox,scrollbar,Wpf,Vb.net,Listbox,Scrollbar,我有一些问题,我将感谢任何帮助 我有一个动态统计列表框的窗口。使用MVVM。对于listbox及其功能,创建了一个带有viewModel的usercontrol。因此,在创建窗口时,我会在窗口的构造函数中创建特定数量的userControls。 事实上,这就是问题所在。 Listbox的最大宽度为350。每个listboxItem最后都带有按钮。 当名称较短时-一切正常,用户可以在加载窗口后看到列表框中的按钮。 但是如果名称太长,listBox会创建一个水平滚动条,因为MaxWidth=350(

我有一些问题,我将感谢任何帮助

我有一个动态统计列表框的窗口。使用MVVM。对于listbox及其功能,创建了一个带有viewModel的usercontrol。因此,在创建窗口时,我会在窗口的构造函数中创建特定数量的userControls。 事实上,这就是问题所在。 Listbox的最大宽度为350。每个listboxItem最后都带有按钮。 当名称较短时-一切正常,用户可以在加载窗口后看到列表框中的按钮。 但是如果名称太长,listBox会创建一个水平滚动条,因为MaxWidth=350(预期行为)。因此,一旦加载表单,一些listBox中似乎没有创建按钮(请参见图2:) 所以问题是:在显示窗口之前,如何以编程方式移动滚动条?图3显示了我需要的内容,图2显示了列表框的当前视图。
你知道如何将滚动条移到最后吗?

谢谢@Yog,谢谢你关于Focus()的提示。我确实没有意识到聚焦方法可以移动滚动条! 我记得我在c#中使用过的方法,我在这个网站上发现了这个方法: 所以我只是把这个方法作为扩展方法重写到vb.net中,在ListBox上调用它,找到了带有按钮的stackPanel,Focus()就是stackPanel! 重要提示:如果有人想用Focus()方法解决他的问题,请确保您的特定xaml元素已设置为Focusable=true

以下是我在Vb.NET上的方法:

Public Function FindChild(Of T As DependencyObject)(parent As DependencyObject, childName As String) As T
        If parent Is Nothing Then Return Nothing

        Dim foundChild As T = Nothing
        Dim childrenCount As Integer = VisualTreeHelper.GetChildrenCount(parent)

        For i = 0 To childrenCount
            Dim child As DependencyObject
            Try
                child = VisualTreeHelper.GetChild(parent, i)
            Catch ex As Exception
                Continue For
            End Try

            'If the child is not of the request child type child
            Dim childType As T = TryCast(child, T)
            If childType Is Nothing Then
                'recursively drill down the tree
                foundChild = child.FindChild(Of T)(childName)
                'If the child is found, break so we do not overwrite the found child.
                If foundChild IsNot Nothing Then Exit For
            Else
                If Not String.IsNullOrEmpty(childName) Then
                    Dim frameworkElement = TryCast(child, FrameworkElement)
                    'If the child's name is set for search
                    If frameworkElement IsNot Nothing AndAlso frameworkElement.Name = childName Then
                        'if the child's name is of the request name
                        foundChild = TryCast(child, T)
                        Exit For
                    End If
                Else
                    'child element found.
                    foundChild = TryCast(child, T)
                    Exit For
                End If
            End If
        Next
        Return foundChild
    End Function

VisualTreeHelper.GetChild方法引发了一个异常,我不知道为什么,所以我把它放到了try catch中。

尝试使用按钮的
Focus()
函数作为
Button2.Focus()
Load
窗口事件(
Form
)如何关注按钮,它是以listBoxItem的样式创建的@你可以看到。我不确定这对你是否有帮助。