Stonetip
Stonetip

Reputation: 1178

Refresh bindings on back navigation using MVVM-Light

Scenario: I start out in my app's main page. I navigate to sub-page A, change a value, hit the back button and the bound TextBlock in the main page doesn't change. If I navigate to sub-page B, a TextBlock using that same binding changes. Likewise, if I go to page A again I see the changed value. If I exit the app, the new value shows up on the main page. It's just when using the back button that a refresh doesn't get triggered.

I've got all my INotifyPropertyChanged stuff working. Like I said, the binding works in every scenario besides navigating back to the main page. How do I send a message or otherwise trigger a refresh of the bindings on that page? Thanks!

Edit:

Based on the accepted answer from willmel, here's what I did:

My MainPage.xaml file has this markup:

<TextBlock Text="{Binding Title, Mode=OneWay}" />

My MainViewModel.cs file has this:

       public string Title
    {
        get { return ProfileModel.Instance.DescriptionProfile.Title; }
    }

And I added this to the MainViewModel constructor:

Messenger.Default.Register<PropertyChangedMessage<string>>(this,
        (action) => DispatcherHelper.CheckBeginInvokeOnUI(
        () => RaisePropertyChanged("Title")));

In another view I have the following markup:

<TextBox Grid.Row="1" Width="250" Height="100" Text="{Binding TitleEdit, Mode=TwoWay}" />

In its view model I use this when getting/setting a string:

        public string TitleEdit
    {
        get { return ProfileModel.Instance.DescriptionProfile.Title; }

        set
        {
            if (ProfileModel.Instance.DescriptionProfile.Title == value) return;

            string oldValue = ProfileModel.Instance.DescriptionProfile.Title;


            ProfileModel.Instance.DescriptionProfile.Title = value;

            RaisePropertyChanged("Title", oldValue, value, true);
        }
    }

Upvotes: 2

Views: 1868

Answers (1)

William Melani
William Melani

Reputation: 4268

In your view model you want to be modified if a child page changes a property. (note here, the property is of type bool, but could be anything)

  Messenger.Default.Register<PropertyChangedMessage<bool>>(this,
    (action) => DispatcherHelper.CheckBeginInvokeOnUI(
   () =>
      {
         MessageBox.Show(action.newValue.ToString());
         //do what you want here (i.e. RaisePropertyChanged on a value they share)
     }));

When you use RaisePropertyChanged in the child class, use the broadcasting overload.

RaisePropertyChanged("Preference", oldValue, value, true);

Finally, note that to use DispatcherHelper, you need to Add the following to your App constructor (App.xaml.cs)

DispatcherHelper.Initialize();

Upvotes: 2

Related Questions