如何在更改 ItemSource 时重新加载 UWP DataGrid

How to reload UWP DataGrid when ItemSource is changed

UWP 数据网格:link

这里是 xaml:

<controls:DataGrid x:Name="dg_Users"
            AlternatingRowBackground="Gainsboro"
            AutoGenerateColumns="False"
            BorderThickness="1"
            CanUserResizeColumns="False"
            GridLinesVisibility="Horizontal"
            IsReadOnly="True"                
            ItemsSource="{Binding UserSource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">

绑定属性:

private ObservableCollection<User> _userSource;
    public ObservableCollection<User> UserSource {
        get { return _userSource; }
        set { SetProperty(ref _userSource, value); }
    }

方法:

//called on constructor
private async void LoadData() {
        UserSource = new ObservableCollection<User>();
        var users = await sqlService.AllUsers();

        if(users != null) {
            foreach (var item in users) {
                UserSource.Add(item);
            }
        }
    }

例如,数据网格将显示 3 个项目,然后我做了一些更改,例如添加了新项目或删除了 1 个项目,当我单击调用 LoadData() 的按钮时,UserSource 已更改并包含新数据,但数据网格不会重新加载或显示 new/updated 数据,如何通过 mvvm 重新加载数据网格?

How to reload UWP DataGrid when ItemSource is changed

请避免在单击每个按钮时重新创建新的 ObservableCollection。请实现 ObservableCollection 对象一次,然后对其进行编辑。请检查以下代码。

public class MainPageViewModel
{
    public ObservableCollection<User> UserSource { get; } = new ObservableCollection<User>();     

    public MainPageViewModel()
    {
        LoadData();        
    }

    private async void LoadData()
    {
        UserSource.Clear();

        var users = await sqlService.AllUsers();

        if (users != null)
        {
            foreach (var item in users)
            {
                UserSource.Add(item);
            }
        }
    }

    public ICommand BtnClickCommand
    {
        get
        {
            return new RelayCommand(() =>
            {
                UserSource.RemoveAt(0);
            });
        }
    }

}

最简单的解决方案:

将 属性 更改为 IEnumerable 作为我的 AllUsers 函数 returns IEnumerable:

private IEnumerable<User> _userSource;
    public IEnumerable<User> UserSource {
        get { return _userSource; }
        set { SetProperty(ref _userSource, value); }
    }

然后加载数据:

private async void LoadUserData() {
        UserSource = await sqlService.AllUsers();
    }

感谢@Clemens