DataGrid正在更新已添加的行,而不是已添加的列

本文关键字:添加 DataGrid 更新 | 更新日期: 2023-09-27 18:26:40

我有一个MVVM应用程序,它的数据绑定DataGrid绑定到Resources<ResourceViewModel>。我通过向DataGrid中显示的资源数据添加了一个附加资源/行

private void OnResourceAddedToCollection(object sender, ResourceCollectionChangedEventArgs e)
{
    var viewModel = new ResourceViewModel(e.NewResource);
    Resources.Add(viewModel);
}

这是有效的。然而,我采取了完全相同的方法,并尝试通过向DataGrid添加列

private void OnResourceCultureCollectionChanged(object sender, 
    ResourceCulturesCollectionChangedEventArgs e)
{
    Resources.Clear();
    foreach (var rvm in e.NewResourceCollection.Select(r => new ResourceViewModel(r)).ToList())
        Resources.Add(rvm);
}

其中事件参数包含更新的底层Resource s。现在我检查了数据,它是正确的——正在添加列,但DataGrid没有显示新列我做错了什么

DataGrid正在更新已添加的行,而不是已添加的列

添加需要重新绘制数据网格的列时,重置DataGrid.ItemSource即可。

视图:

public SomeView(IViewModel vm)
{
    ViewModel = vm;
    DataContext = ViewModel;
    InitializeComponent();
    ViewModel.PropertyChanged += (s, e) =>
    {
        switch (e.PropertyName)
        {
            case "IsResetingColumns":
                if (!ViewModel.IsResetingColumns)
                {
                    dataGrid.ItemsSource = null;
                    dataGrid.ItemsSource = ViewModel.Resources;
                }
                break;
            }
        };
    }

视图模型:

public class ViewModel : INotifyPropertyChanged
{
    private bool _isResetingColumns;
    public bool IsResetingColumns
    {
        get
        {
            return _isResetingColumns;
        }
        set
        {
            if (_isResetingColumns == value)
                return;
            _isResetingColumns = value;
            OnPropertyChanged("IsResetingColumns");
        }
    }
    private void OnResourceCultureCollectionChanged(object sender,
                                                    ResourceCulturesCollectionChangedEventArgs e)
    {
        //VIEWMODEL IS SETTING THIS TO TRUE BEFORE RESETTING `RESOURCES`
        IsResetingColumns = true;
        Resources.Clear();
        foreach (var rvm in e.NewResourceCollection.Select(r => new ResourceViewModel(r)).ToList())
            Resources.Add(rvm);
        //VIEW'S LISTENING TO THIS PROPERTY CHANGED (naming could be better, or an event ,but the gist is there)
        IsResetingColumns = false;
    }