【问题标题】:How to call a method after changed DependencyProperty如何在更改 DependencyProperty 后调用方法
【发布时间】:2012-04-16 06:26:20
【问题描述】:

我有一个使用MVVM 模式的WPF 应用程序。我的项目中有一个窗口,并在我的窗口中使用CustomControl。 我的窗口中需要两个命令来启动和停止 CustomControl 。所以我像这样使用bool DependencyProperty

public static readonly DependencyProperty IsStartModeProperty = DependencyProperty.Register(
    "IsStartMode", typeof(bool), typeof(RadarView), new FrameworkPropertyMetadata(false, OnCurrentReadingChanged));

public bool IsStartMode {
    get { return (bool)GetValue(IsStartModeProperty); }
    set { SetValue(IsStartModeProperty, value); }
}

以下方法也用于我的依赖属性中的回调委托:

public static void OnCurrentReadingChanged(DependencyObject doj, DependencyPropertyChangedEventArgs dp) {
    if (IsStartMode)
        Start();
    else
        Stop();
}

我的问题是在 up 方法中使用 IsStartMode 属性,因为这不是静态的。它有一个构建错误。

我的解决方案是否正确?如果是正确的,我该怎么做?

【问题讨论】:

    标签: c# wpf mvvm custom-controls dependency-properties


    【解决方案1】:

    您需要将第一个方法参数转换为您的 Dependency Object 类:

    public static void OnCurrentReadingChanged(DependencyObject doj, DependencyPropertyChangedEventArgs dp) 
    { 
        var myObject = (RadarView)doj;
    
        if (myObject.IsStartMode) 
            myObject.Start(); 
        else 
            myObject.Stop(); 
    } 
    

    (作为旁注,我将属性称为IsRunning。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      相关资源
      最近更新 更多