Dependency属性更改了回调 - 多次触发

Jak*_*mpl 8 c# windows-phone-8

我想听听DependencyProperty的变化.此代码有效,但每次使用CustomControl重新加载页面后都会调用多次回调方法...

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

视图模型

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

视图

<local:CustomControl IsOpen="{Binding Path=IsOpen}" />
Run Code Online (Sandbox Code Playgroud)

样品

  • 项目

    1. 点按"第二页"
    2. 点击"true"(查看输出窗口)
    3. 回去
    4. 点按"第二页"
    5. 点击"false"(查看输出窗口)

Jak*_*mpl 3

这解决了我的问题。

this.Unloaded += CustomControlUnloaded;

private void CustomControlUnloaded(object sender, RoutedEventArgs e)
{
    this.ClearValue(CustomControl.IsOpenProperty);
}
Run Code Online (Sandbox Code Playgroud)