依赖属性更改了回调 – 多次触发
我想听听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 }
视图
样品
-
项目
- 点按“第二页”
- 点击“true”(查看输出窗口)
- 回去
- 点按“第二页”
- 点击“false”(查看输出窗口)
这解决了我的问题。
this.Unloaded += CustomControlUnloaded; private void CustomControlUnloaded(object sender, RoutedEventArgs e) { this.ClearValue(CustomControl.IsOpenProperty); }
听起来好像触发事件的次数与打开带有控件的页面的次数有关。 这表明您有多个页面实例。
那么问题就是你的网页正在做一些阻止它们被正确销毁的东西。
不幸的是,如果没有能够看到代码,就不可能说出造成这种情况的原因。 可能是您已经订阅了代码中的事件而不是取消订阅它。 (我在手机应用程序中看到了很多。)
发生的事情是SecondPageView
被多次加载。 每次创建新实例时,它都会绑定到数据上下文,并从视图模型中检索IsOpen
的值。 然后设置依赖属性。
这实际上是理想的行为。 如果未再次设置属性,则视图模型的状态将不会反映在页面中。 无法使用手机的本机导航API向前导航到旧页面实例。