Passing value from child window to parent window using WPF and MVVM pattern

后端 未结 2 669
独厮守ぢ
独厮守ぢ 2021-01-15 15:27

I have parent window which has textBox called \"SchoolName\", and a button called \"Lookup school Name\".

That Button opens a child window with list of school names.

2条回答
  •  既然无缘
    2021-01-15 16:15

    My solution is to bind both the windows to the same ViewModel, then define a property to hold the resulting value for codes, lets call it CurrentSchoolCodes, Bind the label to this property. Make sure that CurrentSchoolCodes raises the INotifyPropertyChanged event. then in the DoUseSelectedSchoolNameItem set the value for CurrentSchoolCodes.

    For properties in your models I suggest you to load them as they are required(Lazy Load patttern). I this method your property's get accessor checks if the related field is still null, loads and assigns the value to it. The code would be like this code snippet:

    private ObservableCollection _schoolList;
    public ObservableCollection SchoolList{
        get {
            if ( _schoolList == null )
                _schoolList = LoadSchoolList();
            return _schoolList;
        }
    }
    

    In this way the first time your WPF control which is binded to this SchoolList property tries to get the value for this property the value will be loaded and cached and then returned.

    Note: I have to say that this kind of properties should be used carefully, since loading data could be a time consuming process. And it is better to load data in a background thread to keep UI responsive.

提交回复
热议问题