M
M
Maxim Grekhov2014-01-04 22:59:35
WPF
Maxim Grekhov, 2014-01-04 22:59:35

What is the correct logic for running a DataGrid with MVVM?

Hello. I'm new to WPF and I'm having trouble using a DataGrid using the MVVM template (Catel Framework). In the general case, I wanted to work like this:
In the MyViewModel constructor, a certain data set is obtained through the service, for example, from the database and it is assigned to the ObservableCollection. This collection, in turn, is bound to the DataGrid. In MyViewModel, I create two commands CommitItem and DeleteItem - to commit the change in the value of the item in the database and to delete the item from the database.
In the final version, I got such a DataGrid that performs the above.

public class DataGridEx : DataGrid
    {
        public event EventHandler<EnumerableEventArgs> CommitRow;
        public event EventHandler<EnumerableEventArgs> DeleteRow;

        protected override void OnRowEditEnding(DataGridRowEditEndingEventArgs e)
        {
            base.OnRowEditEnding(e);
            if (e.EditAction == DataGridEditAction.Commit)
            {
                if (e.Row.IsEditing)
                {
                    this.Dispatcher.BeginInvoke(new EventHandler((control, args) =>
                    {
                        if (CommitRow != null)
                            CommitRow(this, new EnumerableEventArgs(e.Row.Item));
                    }), DispatcherPriority.Background, new object[] { this, e });
                }
            }
        }
        protected override void OnExecutedDelete(System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            if (DeleteRow != null)
                DeleteRow(this, new EnumerableEventArgs(SelectedItems));
            base.OnExecutedDelete(e);
        }
    }

But in the process of writing and researching, I learned about validation. The problem now is that the CommitRow event is called regardless of the validation passing.
Question: How to make it work with validation? Or maybe professionals will tell you the correct logic of how DataGrid works with MVVM. I do not understand how it is possible to implement competent addition, removal and editing of elements with validation.
Notes:
I don't want to use Orm due to performance issues.
I looked in the direction of IEditableObject and EndEdit, but I did not like the idea of ​​injecting database dependencies into each element of the model so that it could update itself. How performance will come around if there are a million or more elements.
I understand that you can organize this behavior using a ListView and an additional window for a specific model + add, delete, edit buttons. But it would be desirable to make through one DataGrid element.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question