Answer the question
In order to leave comments, you need to log in
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);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question