开发者

Reflect property change from one ViewModel to another

I have this WPF/MVVM开发者_运维问答 Application that a TabControl with a bunch of tabs. When the app loads, data for all tabs are loaded. There are some calculations that are made on Tab1 that's dependent on values from Tab2. what's happening is, when I enter / change data on tab2, it simply doesn't reflect on Tab1 when I click on Tab1. under the hood, the calculations are made properly but it doesn't reflect on tab1. I have to go to the main tab to re-load all the data to reflect changes. Any ideas how to implement this?


You need to implement INotifyPropertyChanged on your view model data properties. Then, have your view model subscribe to the event (the Initialize() method is called by the view model constructor):

private void Initialize()
{

    // Subscribe to events
    this.PropertyChanging += OnPropertyChanging;
    this.PropertyChanged += OnPropertyChanged;
    this.Books.CollectionChanging += OnBooksCollectionChanging;
}

The view model handler for the event can then update any properties that need to be updated:

void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    switch(e.PropertyName)
    {
        case "FirstProperty":
             this.SomeOtheProperty = whatever;
            break;

        case "Another property":
            this.YetAnotherProperty = somethingElse;
            break;
    }
}

That should get the job done.


If two different ViewModels need to show the same data/value they should bind to the same ViewModel.

I think that adding a binding between ViewModels is bad because it introduces a lot of dependencies.

If a property of a single ViewModel is dependent on an other property of the same ViewModel you could use property changed notification as mentioned in David's answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜