Binding properties between viewmodels

Viewed 56

Lets say I have two views: FileList and Editor. They both have their own view models, bound using a DependencyProperty. The view models look somewhat like this:

public class FileVM : INotifyPropertyChanged
{
    public string FileName { get; set; }
}

public class FileListVM : INotifyPropertyChanged
{
    public ObservableCollection<FileVM> Files { get; set; }
    public FileVM SelectedFile { get; set; }
}

public public class EditorVM : INotifyPropertyChanged
{
    string FileName { get; set; }
}

Imagine that they properly implement INotifyPropertyChanged.

Now I don't want FileListVM and EditorVM to know about each other. They could just as easily exist independently. But in one use case I would like to bind FileListVM.SelectedFile.FileName to EditorVM.FileName. Whenever the selected file or the filename changes, so should the filename in the editor. And whenever the editor changes the filename in the editor, so should the name of the selected file.

Now here is my question: how can I do this cleanly? I'm guessing the solution lies somewhere in their parent view model (e.g. MainVM), since that view model is aware of the connection between the two child view models. But I'm not sure if I can connect the two through xaml, and I'd like to avoid writing property changed event handlers if possible.

1 Answers

Please look at: Communicate between View Models in MVVM

I advise to use MVVM frameworks like Galasoft because they have useful functionality and often do life with MVVM easier ;)

If you do not like using them, you can add event SelectedFileChanged in one VM and subscribe it from the other one.

Related