开发者

Using MVVM style pattern in silverlight/WP7 application

I'm writing an application where I'm attemptin开发者_如何学Pythong to use an MVVM style architecture to handle my data binding (although I'm not using a MVVM specific library, such as MVVM Light). I've got a class which stores all of the information that my application requires, and then each of the screens is assigned a view model to its DataContext, which simply selects the values required for the specific screen, formatting the data if necessary.

As an example, the main data store looks something like this:

class DataStore {
    int a, b, c;
    string d;
    DateTime e;
}

And then the view model allocated to a specific screen, which only uses several of the properties, is something like

class MainScreenViewModel {
    public int data1 { get { return App.DataStore.a * App.DataStore.c } }
    public int data2 { get { return App.DataStore.e.Day } }
}

This seems to work fine, when the page loads the data bindings are populated as they should be. However, they do not update automatically when the page loads. I've implemented INotifyPropertyChanged on the DataStore, but it seems that the change event doesn't bubble through to be reflected in the view model. I'm sure I'm going about this a really bad way, so if anyone could help point me in the right direction I'd be very grateful. I've read a stack of guides online, but I seem to be confusing myself more and more!


You have to implement INotifyPropertyChanged and raise PropertyChanged on your VM. In order to do this you will have to listen for DataStore.PropertyChanged. Sample:

class MainScreenViewModel {
    public int data1 { get { return App.DataStore.a * App.DataStore.c } }
    public int data2 { get { return App.DataStore.e.Day } }


    public MainScreenViewModel()
    {
         App.DataStore.PropertyChanged += (sender, e) => 
                 {
                     if (e.PropertyName == "a" || e.PropertyName == "c")
                         RaisePropertyChanged("data1");
                     if (e.PropertyName == "e")
                         RaisePropertyChanged("data2");
                 };
    }

    private void RaisePropertyChanged(string propertyName)
    {
        // raise it
    }
}

The only part not covered here is the scenario when e.Day will change in DataStore.

Your approach itself is not the bad and is definitely good enough to start with.


You're binding to the MainScreenViewModel class, so it is that class that needs to implement INotifyPropertyChanged for the UI to get updated when the underlying data gets updated.

You could either move the logic into MainScreenViewModel and raise property change notification there, or handle the PropertyChanged event on DataStore in MainScreenViewModel and raise property changed notification for the appropriate properties.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜