我想听听 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!");
}
}
更新
视图模型
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}" />
样本
-
- 点击“第二页”
- 点击“true”(查看输出窗口)
- 回去
- 点击“第二页”
- 点击“false”(查看输出窗口)