Dependency property changed callback - multiple firing

I want to listen to DependencyProperty changes. This code works, but after each reload page, the Callback method is called several times using the CustomControl method ...

public partial class CustomControl : UserControl { public CustomControl() { InitializeComponent(); } public bool IsOpen { get { return (bool)GetValue(IsOpenProperty); } set { SetValue(IsOpenProperty, value); } } public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register("IsOpen", typeof(bool), typeof(CustomControl), new PropertyMetadata(IsOpenPropertyChangedCallback)); private static void IsOpenPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e) { Debug.WriteLine("Fire!"); } } 

Update

ViewModel

 private bool _isOpen; public bool IsOpen { get { return this._isOpen; } set { this.Set(() => this.IsOpen, ref this._isOpen, value); } // MVVM Light Toolkit } 

View

 <local:CustomControl IsOpen="{Binding Path=IsOpen}" /> 

Example

  • project

    • click "second page"
    • click "true" (see output window)
    • return
    • click "second page"
    • tap false (see output window)
+8
c # windows-phone-8
source share
3 answers

This solved my problem.

 this.Unloaded += CustomControlUnloaded; private void CustomControlUnloaded(object sender, RoutedEventArgs e) { this.ClearValue(CustomControl.IsOpenProperty); } 
+3
source share

It appears that the number of times the event fires is related to the number of times you open the page with the control. This assumes that you have multiple instances of the page.

The problem then is that your pages are doing something that prevents them from being destroyed properly.
Unfortunately, unable to see the code, it is impossible to say what causes this. You probably subscribed to the event in code and did not subscribe to it. (I see a lot in phone apps.)

+1
source share

What happens when SecondPageView loads several times. Each time a new instance is created, it is bound to the data context and retrieves the IsOpen value from the view model. Then the dependency property is set.

This is truly desired behavior. If the properties have not been set again, the state of the view model will not be displayed on the page. It is not possible to redirect an old instance of a page using its own phone navigation API.

0
source share

All Articles