Matthew
Matthew

Reputation: 4056

How to Refresh ViewModel in a Page

I am referencing some sample code that queries the device connectivity and returns data regarding how the device is currently connected to the network. I need to determine in the OnNavigatedTo event of a couple pages the current connection mode of the device. I am having trouble getting the ViewModel which grabs the data to refresh when a page is navigated to.

MainPage.xaml.cs

public MainPage()
    {
        InitializeComponent();

        //DataContext = App.DeviceInformationViewModel.InformationProvider;
    }

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        DataContext = null;
        DataContext = App.DeviceInformationViewModel.InformationProvider;
    }

App.xaml.cs

private static DeviceInformationViewModel deviceInformationViewModel = null;

public static DeviceInformationViewModel DeviceInformationViewModel
    {
        get
        {
            // Delay creation of the view model until necessary
            if (deviceInformationViewModel == null)
                deviceInformationViewModel = new DeviceInformationViewModel();

            return deviceInformationViewModel;
        }
    }

DeviceInformationViewModel.cs

private static IInformationProvider informationProvider;

    /// <summary>
    /// Returns the device information to display.
    /// </summary>
    public IInformationProvider InformationProvider
    {
        get
        {
            if (informationProvider == null)
            {
                if (DesignerProperties.IsInDesignTool)
                {
                    informationProvider = new FakeInformation();
                }
                else
                {
                    informationProvider = new RealInformation();
                }
            }

            return informationProvider;
        }
    }

IInformationProvider goes on to provide an interface by which the device network information may be retrieved. I can add those classes as well if need be, they are very short. How would you recommend I update my solution so that every time the MainPage is navigated to the ViewModel may be refreshed and I may update my view with the correct information?

Upvotes: 2

Views: 3670

Answers (1)

har07
har07

Reputation: 89295

Typical way to force binding to check for updated value is by raising property changed notification :

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    App.DeviceInformationViewModel.RefreshProperty("InformationProvider");
}

Assuming you already implemented INotifyPropertyChanged in DeviceInformationViewModel, you can add this method in that VM :

public void RefreshProperty(string propertyName)
{
    NotifyPropertyChanged(propertyName);
}

by raising property changed notification for InformationProvider property, all views bound to that property will be notified to refresh displayed value.

Upvotes: 3

Related Questions