0
votes

I am using mvvm model for my WPF application.

i have a 2 usercontrols in the form 1. Parent ( form with controls) 2. Child ( child has a datagrid to show list of rows which are added from parent form)

but the parent form is dynamic. means controls are not static. For editing if user click on datagrid row in child i need to reload the relevant parent form dynamically.

how to achieve this using MVVM pattern. Both controls have their own view models. please suggest a solution.

3

3 Answers

2
votes

The parent ViewModel needs to be listening to the selection changed events on the child rows. The sample below should explain what I had in mind:

internal class ParentViewModel
{
    private ChildViewModel _child;

    public ParentViewModel(ChildViewModel child)
    {
        _child = child;
        _child.SelectedChildRowChanged += new EventHandler<ChildRowChangedEventArgs>(OnChild_SelectedChildRowChanged);    
    }

    void OnChild_SelectedChildRowChanged(object sender, ChildRowChangedEventArgs e)
    {
        // do your dynamic stuff here
    }
}

internal class ChildViewModel
{
    private ObservableCollection<ChildRowViewModel> _rows;

    public ListCollectionView RowView { get; set; }

    public event EventHandler<ChildRowChangedEventArgs> SelectedChildRowChanged;

    public ChildViewModel(IList<ChildRowViewModel> rows)
    {
        _rows = new ObservableCollection<ChildRowViewModel>(rows);
        RowView = new ListCollectionView(_rows);
        RowView.CurrentChanged += new EventHandler(OnRowView_CurrentChanged);
    }

    void OnRowView_CurrentChanged(object sender, EventArgs e)
    {
        if (SelectedChildRowChanged != null)
        {
            SelectedChildRowChanged(this, new ChildRowChangedEventArgs(RowView.CurrentItem as ChildRowViewModel));
        }
    }
}

internal class ChildRowViewModel
{
}

internal class ChildRowChangedEventArgs : EventArgs
{
    public ChildRowViewModel Row {get; private set;}

    public ChildRowChangedEventArgs(ChildRowViewModel row)
    {
        this.Row = row;
    }
}
1
votes

If you are using MVVM Light from Galasoft then you could use the Messenger class to inform your controls parent about the change. I used this in my project and works like a charm.

I'm sure there are other messaging frameworks too, you just need to Google it. ;)

Galasoft MVVM

0
votes

You should implement INotifyPropertyChanged and use Data Context Proxy to simplify bindings between Controls.