What is the correct way to pass data between view models?

被刻印的时光 ゝ 提交于 2019-12-05 18:14:26

Your ViewModel2 class is depending on the Row --> One possibility to inject the dependency in ViewModel2 is to pass it by constructor.

public class ViewModel1
{
    private DataRowView _dr;
    public DataRowView dr
    {
        get
        {
            return _dr;
        }

        set
        {
            _dr = value;
            OnPropertyChanged("dr");

            this.DetailView = new ViewModel2(value); //On Change of the selected Row create a new viewModel which serves as detail view
        }
    }

    private ViewModel2 _DetailView;
    public ViewModel2 DetailView
    {
        get
        {
            return _DetailView;
        }
        set
        {
            if (_DetailView != value)
            {
                _DetailView = value;
                RaisePropertyChanged(() => this.DetailView);
            }
        }
    }
}

public class ViewModel2
{
    public ViewModel2(DataRowView row)
    {
        this.Row = row;
    }

    private DataRowView _Row;
    public DataRowView Row
    {
        get
        {
            return _Row;
        }
        set
        {
            if (_Row != value)
            {
                _Row = value;
                RaisePropertyChanged(() => this.Row);
            }
        }
    }
}

and in your XAML you can set the datacontext directly to the detail view:

<local:SecondView Margin="499,30,0,20" DataContext="{Binding DetailView, Mode=OneWay}" />

you can use other solution, http://sharedprop.codeplex.com, read the source code is a way to share property between object, and works also if the second object is not active... check just for info

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!