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

UWP中ListView通过x:Bind绑定ItemSource无数据问题求助

解决UWP中x:Bind绑定ListView ItemsSource为null的问题

这个问题的核心原因是x:Bind的默认绑定模式是OneTime,而你是在OnNavigatedTo方法里才实例化ViewModel的——页面初始化时(调用InitializeComponent()的阶段),ViewModel还是null,OneTime绑定只会在初始化时求值一次,后续ViewModel的赋值不会触发绑定更新,所以ListView的ItemsSource一直是null。而后台直接设置ItemsSource是直接给控件赋值,自然能正常工作。

下面给你两种可行的解决方案:

方案一:修改绑定模式+实现页面属性变更通知

这是最贴合你现有MVVM结构的方案,需要两步操作:

1. 让页面实现INotifyPropertyChanged接口,确保ViewModel属性变更时通知绑定

修改LibraryPage.xaml.cs:

using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

public sealed partial class LibraryPage : Page, INotifyPropertyChanged
{
    private LibraryViewModel _viewModel;
    public LibraryViewModel ViewModel
    {
        get => _viewModel;
        set
        {
            if (_viewModel != value)
            {
                _viewModel = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public LibraryPage()
    {
        InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        ViewModel = new LibraryViewModel(KnownFolders.VideosLibrary);
        var source = AdaptiveView.ItemsSource; // 现在这里可以正确获取到Source的值了
    }
}

2. 将XAML中的x:Bind模式改为OneWay

修改LibraryPage.xaml里的ListView绑定:

<ListView ItemsSource="{x:Bind ViewModel.Source, Mode=OneWay}" x:Name="AdaptiveView">
    <!-- 原ItemTemplate内容保持不变 -->
</ListView>

方案二:提前在构造函数中实例化ViewModel

如果你的ViewModel不需要依赖导航参数(或者可以提前获取所需参数),可以直接在页面构造函数里实例化ViewModel,这样InitializeComponent()执行时,ViewModel已经存在,OneTime绑定就能正确获取到Source的值:

修改LibraryPage.xaml.cs:

public sealed partial class LibraryPage : Page
{
    public LibraryViewModel ViewModel { get; set; }

    public LibraryPage()
    {
        ViewModel = new LibraryViewModel(KnownFolders.VideosLibrary); // 提前实例化
        InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        var source = AdaptiveView.ItemsSource;
    }
}

这种情况下XAML里的绑定不需要修改,保持{x:Bind ViewModel.Source}即可。

补充说明

  • 后台直接设置ItemsSource有效,是因为这是直接操作控件的属性,跳过了绑定系统的检测,所以不管绑定状态如何,控件都会立即更新。
  • 如果你ViewModel中的Source是后续异步加载的,只要它是ObservableCollection<Folder>类型,集合内容变化时会自动通知绑定更新,不需要额外处理——这也是ObservableCollection的核心作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:52:05