我希望能监听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!");
}
}
更新
视图模型(ViewModel)
private bool _isOpen;
public bool IsOpen
{
get { return this._isOpen; }
set { this.Set(() => this.IsOpen, ref this._isOpen, value); } // MVVM Light Toolkit
}
视图
<local:CustomControl IsOpen="{Binding Path=IsOpen}" />
示例
-
- 点击“第二页”
- 点击“真”(查看输出窗口)
- 返回
- 点击“第二页”
- 点击“假”(查看输出窗口)