Skip to main content
 首页 » 编程设计

c#之如何在更改 DependencyProperty 后调用方法

2024年02月23日17飞鱼

我有一个使用 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); } 
} 

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

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

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

我的解决方案是否正确?如果我做什么是正确的?

请您参考如下方法:

您需要将第一个方法参数转换为您的依赖对象类:

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

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