简体   繁体   中英

Dependency property changed callback - multiple firing

I want to listen to changes of the DependencyProperty. This code works, but after every reload page with the CustomControl is callback method called multiple times...

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}" />

Sample

  • project

    1. tap "second page"
    2. tap "true" (look at the output window)
    3. go back
    4. tap "second page"
    5. tap "false" (look at the output window)

This solved my problem.

this.Unloaded += CustomControlUnloaded;

private void CustomControlUnloaded(object sender, RoutedEventArgs e)
{
    this.ClearValue(CustomControl.IsOpenProperty);
}

It sounds as though the number of times the event is triggered relates to the number of times that you open the page with the control on it. This would suggest that you have multiple instances of the page.

The issue then is really that your pages are doing something that stop them from being destroyed correctly.
Unfortunately, without being able to see the code it's impossible to say what is causing this. It's probably that you've subscribed to an event in code and not unsubscribed to it though. (I see that a lot in Phone apps.)

What's happening is that the SecondPageView is being loaded multiple times. Each time a new instance is created, it binds to the data context and retrieves the value of IsOpen from the view model. Then the dependency property is set.

This is actually the desired behavior. If the properties were not set again, the view model's state would not be reflected in the page. There is no way to forward-navigate to an old page instance using the phone's native navigation API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM