You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF MVVM中如何通过DataTrigger在歌曲加载完成后聚焦ListBox首项?

WPF MVVM VB.NET 实现列表加载完成后自动聚焦第一项

我用VB.NET开发了一个WPF MVVM应用,启动时ViewModel的构造函数会启动BackgroundWorker加载歌曲列表到ListBox。加载完成后,我希望列表的第一项能自动获得焦点。

由于设置焦点属于纯View层操作,我希望将这部分逻辑放在XAML的代码后置中,ViewModel无需关注焦点相关逻辑。

我尝试过绑定Window和ListBox的各类事件,但要么事件不触发,要么触发时机过早。因此我计划在ViewModel中定义布尔属性InitialSongLoadCompleted,在BackgroundWorker的RunWorkerCompleted方法中将该属性设为True,期望View捕获到属性变化后,调用代码后置中的FocusSongsList方法完成焦点设置。

但我对WPF这部分知识不够熟悉,搜索得知DataTrigger可能实现该需求,但不清楚它的放置位置、正确语法,以及如何触发代码后置函数。同时我也想了解是否存在更简便的实现方式,毕竟这是ViewModel属性变化时触发View操作的基础功能。


代码后置中的焦点设置方法

Private Sub FocusSongsList()
    ' set focus back to the Songs list, selected item (couldn't just set focus to the list, it ran forever and looks like it set focus to every item in turn before releasing the UI)
    Dim listBoxItem = CType(LstSongs.ItemContainerGenerator.ContainerFromItem(LstSongs.SelectedItem), ListBoxItem)
    If Not listBoxItem Is Nothing Then
        listBoxItem.Focus()
    End If
End Sub

ListBox的XAML代码

<ListBox x:Name="LstSongs" ItemsSource="{Binding FilteredSongs}" DisplayMemberPath="Path" 
            HorizontalAlignment="Stretch"
            SelectionMode="Extended" SelectionChanged="LstSongs_SelectionChanged" Loaded="FocusSongsList"/>

ViewModel中的属性定义

Private _InitialSongLoadCompleted As Boolean
Public Property InitialSongLoadCompleted() As Boolean
    Get
        Return _InitialSongLoadCompleted
    End Get
    Set(ByVal value As Boolean)
        _InitialSongLoadCompleted = value
        RaisePropertyChanged("InitialSongLoadCompleted")
    End Set
End Property

内容的提问来源于stack exchange,提问作者Sandra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 19:01:01