2

我有一个 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);
}

其中事件参数保存更新的基础Resources。现在我检查了数据,它是正确的 - 正在添加列,但DataGrid没有显示新列。我究竟做错了什么?

4

1 回答 1

1

添加列时,您需要重新绘制数据网格,重置您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;
    }
于 2013-08-06T16:33:19.690 回答