Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 636
Jakub Krampl Avatar asked Oct 02 '13 06:10

Jakub Krampl


2 Answers

This solved my problem.

this.Unloaded += CustomControlUnloaded;

private void CustomControlUnloaded(object sender, RoutedEventArgs e)
{
    this.ClearValue(CustomControl.IsOpenProperty);
}
like image 109
Jakub Krampl Avatar answered Sep 20 '22 02:09

Jakub Krampl


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.)

like image 38
Matt Lacey Avatar answered Sep 24 '22 02:09

Matt Lacey