我对为依赖外部源的属性创建 DependencyProperty 感到困惑。例如,在我正在编写的超声应用程序中,我目前在Managed C ++包装器中有以下内容(为简单起见,在此转换为C#,实现了INotifyPropertyChanged):

public int Gain
{
    get { return ultrasound.GetParam(prmGain); }
    set 
    { 
        ultrasound.SetParam(prmGain, value);
        NotifyPropertyChanged("Gain");
    }
}

我的所有代码都在WPF中使用,我正在考虑如何将 INotifyPropertyChanged 更改为 DependencyProperty ,如果我从这些更改中受益。有大约30个与此类似的变量,其中大多数变量数据绑定到屏幕上的滑块,文本块或其他控件。

对于为此对象实现 DependencyProperty ,以下内容是否正确?

public int Gain
{
    get { return ultrasound.GetParam(prmGain); }
    set 
    { 
        ultrasound.SetParam(prmGain, value);
        this.SetValue(GainProperty, value); 
    }
}

public static readonly DependencyProperty GainProperty = DependencyProperty.Register(
    "Gain", typeof(int), typeof(MyUltrasoundWrapper), new PropertyMetadata(0));

我从未见过没有使用 this.GetValue(GainProperty)的例子。此外,还有其他功能可能会更改该值。这也是正确的改变吗?

public void LoadSettingsFile(string fileName)
{
    // Load settings...

    // Gain will have changed after new settings are loaded.
    this.SetValue(GainProperty, this.Gain);
    // Used to be NotifyPropertyChanged("Gain");
}

此外,另外,在大多数属性是数据绑定的情况下,或者更确切地说,在许多参数不是数据绑定的情况下,我是否应该期望性能提升?

有帮助吗?

解决方案

当使用依赖项属性时,Get和Set方法必须只是this.GetValue()和this.SetValue()的简单包装器,原因是WPF不使用getter或setter来访问值,所以你不能依赖于一直运行的额外代码。

如果你确实需要这些属性作为依赖属性,那么创建一个标准的依赖属性,它有效地缓存你的超.GetParam(prmGain)结果,并在PropertyChanged事件中调用Ultras.SetParam(prmGain,value),它将被可靠地称为no无论房产如何变更。


虽然我上面写的内容仍然是正确的,重读你的问题让我觉得你可能误解了依赖属性是什么。如果这个C ++包装器对象实际上是你的模型,那么你想继续使用INotifyPropertyChanged。依赖属性旨在由内部的WPF控件使用,以便于绑定并降低控件的内存占用。它们不应该在数据提供者中使用,这是通知接口的用途。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top